Answer the question
In order to leave comments, you need to log in
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>
//Поля формы
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!');
}
$('#create-order-form').on('afterValidate',function(){
$.pjax.defaults.timeout = 3000;
$.pjax.reload({container: '#form-errors'});
});
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question