验证失败后打印错误消息

时间:2014-01-29 10:39:16

标签: yii

我是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";

我收到“只读”错误....

1 个答案:

答案 0 :(得分: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');
    }     
}
相关问题