CakePHP extra check for file upload

How to make file upload optional with verification? The code below checks even if I have not selected any files. I want to check the extension only if I selected the file. If I do not select any file, it should not return verification errors.

class Catalog extends AppModel{
    var $name = 'Catalog';
    var $validate = array(
        'name' => array(
            'rule' => '/^[a-z0-9 ]{0,}$/i',
            'allowEmpty' => false,
            'message' => 'Invalid Catalog name'
        ),
        'imageupload' => array(
            'rule' => array('extension',array('jpeg','jpg','png','gif')),
            'required' => false,
            'allowEmpty' => true,
            'message' => 'Invalid file'
        ),
       );
}

early

+3
source share
2 answers

"I assign $ this-> data ['Catalog'] ['image'] = $ this-> data ['Catalog'] ['imageupload'] ['name'];"

So, by the time you save your data array, it looks something like this, I assume:

array(
    'image' => 'foobar',
    'imageupload' => array(
        'name' => 'foobar',
        'size' => 1234567,
        'error' => 0,
        ...
     )
)

, imageupload :

array(
    'name' => 'foobar',
    'size' => 1234567,
    'error' => 0,
    ...
 )

.. , , , . . , , "".

, , , .

+2

:

( ) , - . , .

:

// is any image uploaded?
$isNoFileUploaded = ($this->request->data['Model']['field_name']['error'] == UPLOAD_ERR_NO_FILE) ? true : false ;
if ($isNoFileUploaded) {
    $this->Model->validator()->remove('field_name');
}

:

( , ), @deceze answer

+1

Source: https://habr.com/ru/post/1752398/


All Articles