Yii 验证失败后打印错误消息
我是Yii的新手。我有一个用户可以发布文章的表单。我想确保只有在前一篇文章的发布日期超过一小时后,用户才能发布文章 因此,在模型中,我有:Yii 验证失败后打印错误消息,yii,Yii,我是Yii的新手。我有一个用户可以发布文章的表单。我想确保只有在前一篇文章的发布日期超过一小时后,用户才能发布文章 因此,在模型中,我有: protected function beforeSave() { //get the last time article created. if more than an hour -> send $lastArticle = Article::model()->find(arra
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";
我收到一个“只读”错误….因为您正在描述一个验证规则,所以在保存之前,您应该将此代码放在自定义验证规则中,而不是放在
中。这将解决以下问题:
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');
}
}
因为您描述的是验证规则,所以应该将此代码放在自定义验证规则中,而不是在保存之前放在中。这将解决以下问题:
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');
}
}
因为您描述的是验证规则,所以应该将此代码放在自定义验证规则中,而不是在保存之前放在中。这将解决以下问题:
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');
}
}
因为您描述的是验证规则,所以应该将此代码放在自定义验证规则中,而不是在保存之前放在中。这将解决以下问题:
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');
}
}