2016-04-27 49 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)); 
      }) 
     });