1
votes

How to get an input type file to validate for notempty in cake?

When you submit the form without adding a file the validation says it is empty even though $this->request->data shows the file.

// Model/Product.php

class Product extends AppModel {
  public $validate = array(
    'name' => array(
        'rule' => 'notEmpty'
    ),
 );

}

// Controller/ProductController.php

 public function add() {
    if ($this->request->is('post')) {
        $this->Product->create();
        if ($this->Product->save($this->request->data)) {
            $this->Session->setFlash('Your product has been saved.');
        } else {
            $this->Session->setFlash('Unable to add your product.');
            debug($this->request->data);
            debug($this->Product->validationErrors);
        }
    }
}

// View/Products/add.ctp

echo $this->Form->create('Product', array('type' => 'file'));
echo $this->Form->input('name', array('type' => 'file'));
echo $this->Form->end('Save Post');
1

1 Answers

3
votes

I don't think that you can actually use notEmpty on the -somewhat special- file field. The file field is handled differently than any other input field, as it returns the superglobal $_FILES as a result. As such, you should check it a little bit differently. There is actually quite a good example in the CakePHP Documentation.

Now this is for actually uploaded files, but you can easily change it by checking if the name key is not empty and actually set. Something like this as a custom validation rule in your Model should do the trick:

public function fileSelected($file) {
    return (is_array($file) && array_key_exists('name', $file) && !empty($file['name']));
}

And then just set this as validation rule for your file field:

public $validate = array(
   'name' => array(
       'rule' => 'fileSelected'
   ),
);