cakephp文件notempty验证 - 错误?

时间:2012-10-20 11:17:05

标签: cakephp

如何获取输入类型文件以验证蛋糕中的notempty?

当您在不添加文件的情​​况下提交表单时,验证表明它是空的,即使$ this-> request->数据显示该文件。

// 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);
        }
    }
}

//查看/ 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 个答案:

答案 0 :(得分:3)

我认为你不能在-somewhat特殊文件字段上使用notEmpty。文件字段的处理方式与任何其他输入字段的处理方式不同,因为它返回超全局$ _FILES作为结果。因此,您应该稍微检查一下。 CakePHP Documentation中有一个很好的例子。

现在这是针对实际上传的文件,但您可以通过检查name键是否为空并实际设置来轻松更改它。像这样的模型中的自定义验证规则可以解决这个问题:

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

然后将其设置为文件字段的验证规则:

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