2013-08-05 26 views
0

我想使用Form Builder來建立一個簡單的文件上傳提示。我想指定該文件的規則類似於Yii文件CFormInputElement將不會顯示,除非明確標記爲「安全」

array('formFile', 'file', 'allowEmpty' => false, 'types' => 'html'), 

但是有些錯誤。僅當我明確將元素標記爲'safe'(並刪除'file'規則)時纔會出現文件上載元素。我錯過了什麼?

模型/ UploadForm.php

class UploadForm extends CFormModel 
{ 
    public $year; 
    public $formFile; 

    public function rules() 
    { 
     return array(
      array('year', 'required'), 
      array('year', 'date', 'format'=>'yyyy'), 
//   array('formFile', 'safe'), 
      array('formFile', 'file', 'allowEmpty' => false, 'types' => 'html'), 
     ); 
    } 

    static public function getYearOptions() {...} 
} 

視圖/外聯網/ uploadForm.php

return array(
    'title' => 'Select year', 
    'method' => 'post', 
    'enctype' => 'multipart/form-data', 

    'elements' => array(
     'year' => array(
      'type' => 'dropdownlist', 
      'items' => UploadForm::getYearOptions(), 
     ), 
     'formFile' => array(
      'type' => 'file', 
      'label' => 'form source file', 
     ), 
    ), 

    'buttons' => array(
     'upload' => array(
      'type' => 'submit', 
      'label' => 'upload', 
     ), 
    ), 
); 

控制器/ ExtranetController.php

class ExtranetController extends CController 
{ 
    public function actionIndex() 
    { 
     $form = new CForm('application.views.extranet.uploadForm', new UploadForm()); 
     if ($form->submitted('upload') && $form->validate()) {...} 
     $this->render('index', array('form' => $form)); 
    } 
} 

回答

1

原因很簡單。

表單構建器僅呈現被認爲安全的輸入元素(I.E.具有驗證規則)。你所做的完全沒問題,除非CFileValidator在默認情況下不是「安全的」,而其他驗證器是安全的。

解決這個最快捷的方法是:

// In your model::rules() function 
return array(
    array('formFile', 'file', 'allowEmpty' => false, 'types' => 'html', 'safe' => true), 
); 

參考這兩個環節的詳細信息:the CFileValidator#safe documentation,和the Github issue for a problem very similar to yours

+0

我知道這是問題,而不是如何解決它。我沒有考慮合併這兩條規則。謝謝! – N13