繁体   English   中英

在服务器端收集CActiveForm错误

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM