0

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....

0

1 Answer 1

3

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');
    }     
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.