2013-04-21 59 views
0

我有一個CActiveForm本摘要:收集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

回答

1

我用這樣的事情在控制器:

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();  
       } 
     } 

你可以用它代替jQuery函數ajaxSubmitButton。類似這樣的:

<?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. 
    ));?> 

希望這對我有所幫助。

+0

** @ ineersa ** [here](http://stackoverflow.com/questions/16140172/when-ajaxvar-initialized-in-cactiveform)討論了主要問題。 – msoa 2013-04-22 07:56:00