[英]Collecting CActiveForm Errors On Server-Side
我有一個帶有以下摘要的CActiveForm
:
.
.
.
'id'='email-form',
'enableAjaxValidation`=>true,
'clientOptions' => array('validateOnSubmit'=>true),
.
.
.
現在,我打算在服務器端收集表單錯誤並將其通過json object
發送給客戶端。 在客戶端中,有一個Jquery函數,它解析json object(form Errors)
並將數據設置為errorSummary,最后顯示form的errorSummary。
我做到了沒有任何問題,我的問題是以下哪些函數無法收集表單錯誤:
protected function getErrorSummary($model)
{
if(isset($_POST['ajax']) && $_POST['ajax']==='email-form'){
$errors=CActiveForm::validate($model);
if($errors !== '[]')
Yii::app()->end($errors);
}
}
但是下面收集表單錯誤:
protected function getErrorSummary($model)
{
$errors=CActiveForm::validate($model);
if($errors !== '[]')
Yii::app()->end($errors);
}
注意,這兩個函數真正作用於validateOnChange
。
我在控制器中使用了以下內容:
if(Yii::app()->request->isAjaxRequest)
{
$error=CActiveForm::validate($model);
if($error!='[]'){
echo $error;
Yii::app()->end();
}
}
if(isset($_POST['Lists']))
{
$model->attributes=$_POST['Lists'];
if($model->save())
{
echo CJSON::encode(array(
'status'=>'success',
));
Yii::app()->end();
}
}
您可以使用ajaxSubmitButton代替jquery函數。 像這樣:
<?php echo CHtml::ajaxSubmitButton ($model -> isNewRecord ? 'Create' : 'Save' , Yii::app()->request->url, array (
'dataType' => 'json',
'type'=>'post',
'success' =>
'js:function (data) {
if(!$.isEmptyObject(data)) {
$.each(data, function(key, val) {
$("#lists-form #"+key+"_em_").text(val+" ");
$("#lists-form #"+key+"_em_").parent(".error_wrapter").addClass("error");
$("#lists-form #"+key+"_em_").css(\'display\',\'block\');
});//here you show your errors on form fields from JSON object
};
if(data.status=="success"){
//here you can use custom notifications or redirect
}
else {
//here you can display errorsummary or notifications
};
}',
), array (
'id' => 'lists-form_submit_'.rand(1,255), // Need a unique id or they start to conflict with more than one load.
));?>
希望這會有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.