A
A
Artemmmm132020-09-29 20:16:08
JavaScript
Artemmmm13, 2020-09-29 20:16:08

How to get form validation ajax errors outside Yii2's field method?

It is necessary to implement saving data without reloading the page, so errors should also be displayed without reloading. Implemented the following validation:

<?php $form = ActiveForm::begin([
        'id' => 'create-order-form',
        'enableAjaxValidation' => true,
        'validateOnSubmit' => true,
        'validateOnType' => false,
        'validateOnChange' => false,
        'validationUrl' => Url::toRoute(['/order/validate-form']),
        'options' => [
            'class' => 'order-form',
        ],
        'fieldConfig' => [
            'options' =>
            [
                'tag' => false,
            ]
        ],
    ])?>
    <div class="row">
//Тут хочу вывести ошибки
    <?php Pjax::begin(['id' => 'form-errors']);?>
        <?php if($model->hasErrors()):?>
            <?php foreach ($model->getErrors() as $key => $value):?>
                <div class="alert alert-danger w-100 text-center" role="alert">
                    <?= $value[0];?>
                </div>
            <?php endforeach;?>
        <?php endif;?>
    <?php Pjax::end();?>
    </div>
//Поля формы

Validation method:
public function actionValidateForm()
    {
        if(Yii::$app->request->isAjax) 
        {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

            $model = new CreateOrder();

            if($model->load(Yii::$app->request->post()))
            {
                return ActiveForm::validate($model);
            }
        }
        
        throw new \yii\web\BadRequestHttpException('Bad request!');   
    }

js code that should update pjax
$('#create-order-form').on('afterValidate',function(){

    $.pjax.defaults.timeout = 3000;

    $.pjax.reload({container: '#form-errors'});
  });

Errors come in the console, but for some reason they do not appear in the block where I want to display errors. The fact is that the standard error output does not suit me, so I removed the error fields in the 'template' and want to display it separately.
I think the mistake is that I'm not displaying them correctly. The documentation and forums show how to do ajax validation, but I have not found anywhere how to get errors apart from the ActiveForm field method.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexandr Pit, 2020-10-01
@AlexPitTech

in this case, you should decide whether you are pjax loading the page (the actionValidateForm method will not help you in any way), or you are ajax validating the form (pjax will not help you here).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question