2012-12-27 38 views
0

即時通訊有點新, 我有一個屬性file_id模型,但它會顯示爲文件。我應該強制這個..但是當用戶上傳一個文件時,我將文件路徑存儲在文件表中。並從該表中獲取id並將其存儲在我的模型中。如何使文件上傳強制yii

誰能請告訴我,我怎樣才能使文件上傳強制創造而不是更新

我的文件上傳代碼:

   <?php echo $form->labelEx($model,'file'); ?> 
       <?php echo $form->fileField($model, 'file');?> 
       <?php echo $form->error($model,'file'); ?>` 

其工作的罰款。但是我需要爲這個當前模型強制它。我是否需要在文件模型或當前模型中的規則函數中使用它?

感謝,

回答

1

最簡單的方法是在模型的規則:

array('file', 'required','on'=>'insert'), 

然後只需要在插入時和不更新。

另一種方法是利用之前或afterValidate方法:

protected function afterValidate(){ 
    if($this->isNewRecord){ 
     if(!isset($this->file)){ //Not sure about handling files if this works. 
      $this->addError("file","Not file selected. Please choose a file to upload."); 
      return false; 
     } 
    } 
    return parent::afterValidate(); 
} 
+0

IM存儲在其他模型(表),但該文件中獲取其ID,並在我的模型存儲文件ID – Developer

+1

的問題是,如果我不要求使用它的工作正常。如果我使用這個:array('file','required','on'=>'insert')或array('file','required'),它再次說文件不能爲空(即使我上傳文件):( – Developer

+0

嘗試「創建」而不是插入。我認爲這是正確的上下文。 –