2014-01-29 2 views
0

Im new to 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'); 
    }  
} 
관련 문제