Asynchronous validation of ActiveForm ajax form in yii2 modal pop-up window, yii2activeform
The previous section describes how to use modal in yii2 and how to use modal in the update operation in the yii2 gridview list. I thought that modal would come to an end to start a new topic, but the actual problem is often beyond imagination. This is not the case that the form submitted by modal pop-up window says that the question of how to verify has come out again!
Let's leave modal aside. Let's give a simple description of how yii2 ActiveForm submits forms in Ajax mode. This is also the focus of our topic today. modal is really nothing to say. If I had to change it back later.
In yii2, ActiveForm performs client verification by default, but the form submission is not refreshing. That is, after the forms are submitted, the page is refreshed. To enable the refreshing mode, you only need to enableAjaxValidation in ActiveForm, as shown below:
<?php $form = ActiveForm::begin(['id' => 'form-id','enableAjaxValidation' => true,]); ?>
Note: Neither id nor enableAjaxValidation can be less.
Next, let's look at the implementation of the server.
if ($model->load(Yii::$app->request->post())) {Yii::$app->response->format = yii\web\Response::FORMAT_JSON;if ($errors = \yii\widgets\ActiveForm::validate($model)) {return $errors;} else {if($model->save(false)) {return $this->redirect(['index']); }}}return $this->render('create', ['model' => $model,]);
In this way, yii2 is implemented asynchronously without refreshing new forms!
In fact, it doesn't matter whether it is mentioned or not. It mainly serves as a reference for some lazy people. After reading the title, smart people should understand how to solve the problem of modal submitting forms through ActiveForm.
To be compatible with modal, note that we are talking about compatibility rather than implementation. We have made some changes to the program for reference only.
if ($model->load(Yii::$app->request->post())) {if ($model->save()) { if (Yii::$app->request->isAjax) {Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;return ['success' => true];}return $this->redirect(['index']);} else {if (Yii::$app->request->isAjax) {Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;return \yii\widgets\ActiveForm::validate($model);}}}if (Yii::$app->request->isAjax) {return $this->renderAjax('create', ['model' => $model,]);} else {return $this->render('create', ['model' => $model,]);}
The above is a small Editor to introduce you to the yii2 modal pop-up window ActiveForm ajax form verification knowledge, hope to help you, if you want to learn more, please stay tuned to the help House website!