We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

File Upload / Form Validation

Hi, I am trying to validate a File field in my form and it is always giving me empty error.

Here is my file field in the form

$facilityimage = new File('facilityimage');

$facilityimage->addValidators([
    new \Phalcon\Validation\Validator\File([
        'maxSize' => '0.5M',
        'messageSize' => 'Your image is too big. Max file size: 500KB',
        'allowedTypes' => array('image/jpeg', 'image/png'),
        'messageType' => 'Your image must be a JPEG or PNG file',
        'messageEmpty' => 'No image uploaded'
    ])
]);

$this->add($facilityimage);

In my Action, I have tried passing $_POST and $_FILES as follows:

if (!$form->isValid(array_merge($this->request->getPost(), $this->request->getUploadedFiles(true)))) {
    foreach ($form->getMessages() as $message)
        $this->flash->error((string) $message);
}

I have checked the forums and none of the solutions provided is working for now. I am using Phalcon 4.

Ok it is working with $_FIles instead of $this->request->getUploadedFiles(true).

In my opinion it should work with native Phalcon alternative of $_FILES.

Another Question Documentation showing messageFileEmpty variable for setting empty message however both messageFileEmpty as well as messageEmpty are not being overriden in forms. Only default message is being shown.

Any help will be appreciated.



5.9k
Accepted
answer

Here is my final code to achieve the goal:

Form element:

$fImage = new File('image');

$fImage->addValidators([
    new FileValidator([
        'maxSize' => '0.5M',
        'messageSize' => 'Your image is too big. Max file size: 500KB',
        'allowedTypes' => array('image/jpeg', 'image/png'),
        'messageType' => 'Your image must be a JPEG or PNG file',
        'equalResolution' => '130x80',
        'messageEqualResolution'    => 'Image resolution should be 130px by 80px.',
        'allowEmpty' => (!empty($options['edit']) ? true : false)
    ])
]);

$this->add($fImage);

In Controller:

if ($this->request->isPost()) {
    // Workaround as image gets updated with $_FILES
    $facilityImage = $facility->image;
    // End Workaround

    $validationArray = $this->request->hasFiles() ? array_merge($this->request->getPost(), $_FILES) : $this->request->getPost();
    if (!$form->isValid($validationArray)) {
        foreach ($form->getMessages() as $message)
            $this->flash->error((string) $message);

        // Workaround as facilityimage gets updated with $_FILES
        $facility->image = $facilityImage;
        unset($facilityImage);
        // End Workaround
    } else {
    // Success Code goes here
    }
}