2012-10-20 44 views
1

如何獲得輸入類型文件來驗證蛋糕中的notempty?cakephp文件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'); 

回答

3

我不不要以爲你可以在某些特殊文件領域使用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' 
    ), 
);