Reputation: 1073
Im new to Yii. I have a form where users can publish an article. I want to make sure users can only publish an article if the publish date of the previous article is more than an hour ago.
So in the model I have:
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 works, but how do I display an error message on the form? If i try to set error with:
$this->errors = "Must be more than an hour since last published article";
I get a "read only" error....
Upvotes: 0
Views: 123
Reputation: 437336
Since you are describing a validation rule, you should be putting this code in a custom validation rule instead of in beforeSave
. This will take care of the problem:
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');
}
}
Upvotes: 3