【问题标题】:cakephp file notempty validation - bug?cakephp 文件 notempty 验证 - 错误?
【发布时间】:2012-10-20 11:17:05
【问题描述】:

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

当您提交表单而不添加文件时,即使 $this->request->data 显示该文件,验证也会显示该表单为空。

// 型号/Product.php

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

}

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

//查看/产品/add.ctp

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

【问题讨论】:

    标签: cakephp


    【解决方案1】:

    我认为您实际上不能在 -somewhat special- 文件字段上使用 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'
       ),
    );
    

    【讨论】:

      猜你喜欢
      • 2015-11-26
      • 1970-01-01
      • 1970-01-01
      • 2016-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      相关资源
      最近更新 更多