2014-01-29 44 views
0

Im新的Yii。我有一個表單,用戶可以發佈文章。我想確保用戶只有在上一篇文章的發佈日期超過一個小時之前才能發佈文章。驗證失敗後打印錯誤消息

因此在模型中我有:

protected function beforeSave() 
    { 
     //get the last time article created. if more than an hour -> send   
     $lastArticle = Article::model()->find(array('order' => 'time_created DESC', 'limit' => '1')); 

     if($lastArticle){ 
      if(!$this->checkIfHoursPassed($lastArticle->time_created)){ 
       return false; 
      } 
     } 

     if(parent::beforeSave()) 
     { 
      $this->time_created=time(); 
      $this->user_id=Yii::app()->user->id; 

      return true; 
     } 
     else 
      return false; 
    } 

這工作,但我如何在窗體上顯示一條錯誤消息?如果我嘗試設置誤差:

$this->errors = "Must be more than an hour since last published article"; 

我得到一個「只讀」的錯誤....

回答

3

因爲你所描述的驗證規則,你應該把這個代碼在一個自定義的驗證規則而不是在beforeSave。這將處理該問題:

public function rules() 
{ 
    return array(
     // your other rules here... 
     array('time_created', 'notTooCloseToLastArticle'), 
    ); 
} 

public function notTooCloseToLastArticle($attribute) 
{ 
    $lastArticle = $this->find(
     array('order' => $attribute.' DESC', 'limit' => '1')); 

    if($lastArticle && !$this->checkIfHoursPassed($lastArticle->$attribute)) { 
     $this->addError($attribute, 
         'Must be more than an hour since last published article'); 
    }  
}