Home > Article > Backend Development > Obtain error information for rules verification in Yii CModel, yiicmodel_PHP tutorial
<span>在model中定义 </span><span>public</span> <span>function</span><span> rules(){ </span><span>return</span> <span>array</span><span>( </span><span>array</span>('Name,Email','required'), <span>array</span>('Email','unique','message'=>'{value}出错啦'),//<span>{value}为添加的数据 ); } controller中使用 </span><span>$model</span> = <span>new</span> myModel();<span>//</span><span>实例化相关表的模型类</span> <span>$model</span>->attributes = <span>$_POST</span> <span>//</span><span>对attributes赋值为提交上来(需要验证)的数据,字段为rules中safe</span> <span>$model</span>->validate();<span>//</span><span>这里会自动调用验证规则rules</span> <span>$model</span>->getErrors();<span>//</span><span>获取所有验证字段的错误信息</span> <span>$model</span>->getErrors('Email');<span>//</span><span>获取当前传入字段的错误信息</span> <span>$model</span>->getError('Email');<span>//</span><span> 'message信息' </span>
This uses
CHtml::errorSummary($model1)
You can check the manual and it will return a string
The description of your problem is not very clear, so I will tell you about Yii form verification!
For Yii form verification, you can refer to the actionContact method of the blog SiteController in its demos:
public function actionContact()
{
$model=new ContactForm;
if(isset( $_POST['ContactForm']))
{
$model->attributes=$_POST['ContactForm'];
if($model->validate())
{
$headers="From: {$model->email}\r\nReply-To: {$model->email}";
mail(Yii::app()->params[' adminEmail'],$model->subject,$model->body,$headers);
Yii::app()->user->setFlash('contact','Thank you for contacting us . We will respond to you as soon as possible.');
$this->refresh();
}
}
$this->render('contact',array( 'model'=>$model));
}
I won't list the model part here, just take a look at its demo for yourself!
This method is after the form is submitted
if(isset($_POST['ContactForm'])) determines whether the form is submitted
$model->attributes=$_POST['ContactForm' ]; Assign the form data to the model attribute
if($model->validate()) This step is to call the verification in the model. If there is an error, an error will be returned, which will reload the view. In this way, the error part of the form displayed in the view will have an error output!
1474dfd8d57635c571d65b829fea6344errorSummary($model); ?>
This part comes from the error output part in the view!