E
E
EVOSandru62017-08-05 21:31:11
Yii
EVOSandru6, 2017-08-05 21:31:11

How to intercept response in ajax form Validation in Yii2?

Good afternoon,
There is such a form :

$form = ActiveForm::begin([
                'id'=>$model->formName(),
                'validationUrl'=>Url::to(['/orders/default/validation']),
                'enableAjaxValidation'=>true,
                'enableClientValidation'=>true,
                'validateOnBlur'=>true,
                'validateOnChange'=>true,
                 'fieldConfig' => [
                     'template' => '<div class="c-order-checkout__group">{label}{input}{error} </div>',
                     'inputOptions'=>[
                         'class'=>'form-control h-form__input h-input-response'
                     ],
                     'options' => [
                         'tag' => false,
                     ],
                 ]
            ]);

ValidateAction :
class ValidationAction extends Action
{
    public function run() // $id
    {
        $model = new $this->modelClass;
        if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model); 
        }
    }
}

When you click the Submit button of the form, Chrome's Firebug XHR contains the response as JSON :
{"orders-user_name":["Необходимо заполнить «user-name»."],"orders-user_phone":["Необходимо заполнить «Телефон»."],"orders-user_email":["Необходимо заполнить «e-mail»."],"orders-customer_id":["Необходимо заполнить «Пользовать»."]}

But these errors are not automatically displayed in blocks with help-block classes next to form fields. Does it mean you have to implement it yourself? Or did I mess up somewhere? I dug up this Jquery
script :
$.each(data, function(key, val) {
      $('#'+key).after('<div class='help-block'>'+val+'</div>');
      $('#'+key).closest('.form-group').addClass('has-error');
});

But I don't know where to put it? Tell me please.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Timofeev, 2017-08-07
@EVOSandru6

There are events that activeForm throws, for example:

$('form').on('afterValidateAttribute', function(event, attr, msg) {
        console.log(event);
        console.log(attr);
        console.log(msg);
    });

In addition, you can prescribe js in the rules settings:
['title','string','max'=>400, 'whenClient'=>function (attribute, value) {
    return $('#country').val() === 'USA';
}]

read more here: www.yiiframework.com/doc-2.0/yii-validators-valida...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question