1
votes

I have made an Active form with validation and ajax submit.

The form is created in view:

 <?php $form = ActiveForm::begin([
        'id' => 'login-form',
        'layout' => 'horizontal',
        'method' => 'post',
        'enableClientValidation' => false,
        'enableAjaxValidation' => true,
        'validationUrl' => 'panel/validate',
        'fieldConfig' => [
            'options' => [
                'tag' => false,
            ],
             'template' =>'{input}<p class="help-block help-block-error ">{error}</p>'
        ],
    ]); ?>

The validation action:

 public function actionValidate()
    {
        $model = new LoginForm();
        $request = \Yii::$app->getRequest();

        if ($request->isAjax && $request->isPost && $model->load(Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
        return $this->renderAjax('login', [
            'model' => $model,
        ]);
    }

When i leave the fields blank for example, or do not specify the captcha i can see the ajax response:

{"loginform-username":["Username cannot be blank."],"loginform-password":["Password cannot be blank."],"loginform-captcha":["Captcha cannot be blank."]}

However, those errors not getting shown under my form fields. The form fields are created like this:

 <?= $form->field($model, 'username')->textInput()

If i turn off ajax validation, the erros are displayed. What can be wrong here?

1

1 Answers

2
votes

I'm afraid there is no possible way to display error while turning off 'tag' = false in fieldConfig.

Even though it works for server-side validation, the main problem is how yii.activeForm.js updateInput() function for fields works. When ajax request is completed, the .js tries to find an outer tag (of field) with .field-<model>-<attribute> class selector and fetch error-div children. As long as there is no outer .field tag, no error message is append to form.

I'm not 100% sure about it, but this is my understanding from debugging yii.activeForm.js functionality.

Actually, here is the similar question in yii2/issues, where SilverFire explains that there is no way to achieve this.
ActiveForm fieldConfig options tag=>false will render class attribute without any tag