2016-04-27 46 views
0

我有5種不同型號的形式是在一個單一的控制器使用Ajax驗證:Yii2 - 阿賈克斯的ActiveForm驗證不顯示錯誤

public function performAjaxValidation($model1, $model2, $model3, $model4, $model5) { 
    Yii::$app->response->format = Response::FORMAT_JSON; 
    return ActiveForm::validateMultiple([$model1, $model2, $model3, $model4, $model5]); 
} 

對於每一個模型,我有一個像「唯一」的規則:

[['COUNTRY_LABEL'], 'required', 
    'when' => function ($model) { 
     return ($model->COUNTRY_ID == 0) || is_null($model->COUNTRY_ID); 
    }, 'whenClient' => "function (attribute, value) { 
     return ($('#country-country_id').val() == 0) || ($('#country-country_id').val() == \"\"); 
    }"], 

[['COUNTRY_LABEL'], 'unique', 'message' => 'Country already exist.')], 

更多...

和單一視圖:

  <?php 
      $form = ActiveForm::begin([ 
         'options' => ['enctype' => 'multipart/form-data',], 
         'enableAjaxValidation' => true, 
      ]); 
      ?> 
      <?= $form->field($countryModel, 'COUNTRY_LABEL')->textInput(['maxlength' => true]) ?> 

JSON工作正常,我可以在我的視圖中看到「不能爲空」的消息。 當我想測試'COUNTRY_LABEL'是否是唯一的,JSON返回'國家已經存在',但不要在視圖中顯示我的消息。

我做錯了什麼?

回答

1

首先,你需要在你的表單配置id

$form = ActiveForm::begin([ 
    'id' => 'contact-form', 
    'enableAjaxValidation' => true, 
]); 

您還需要準備服務器,以便它可以處理Ajax請求驗證。這可以通過一個代碼片斷一樣在控制器的動作以下操作來實現:

if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) { 
    Yii::$app->response->format = Response::FORMAT_JSON; 
    return ActiveForm::validate($model); 
} 

最後,這是我用來處理在我看來,返回的JSON結果(在這種情況下,迭代data來一補選擇字段):

 $.post('" . Yii::$app->urlManager->createUrl('some/action') . "', {id: $('#someform-attrib_id').val()}, function (data) { 
      $.each(data, function (key, obj) { 
       someSelect.append($('<option>').val(obj.id).text(obj.name)); 
      }) 
     });