This article mainly This article introduces the relevant information of Yii2 to implement ActiveForm ajax submission in detail, which has certain reference value. Interested friends can refer to
When doing projects, you will always encounter the ajax submission function, especially in When doing background submission, the model is usually automatically generated. This function is used more frequently. In fact, as long as you understand the process, the operation is quite simple and convenient to use.
Form part
<?php $form = ActiveForm::begin([ 'action' => ['save'], //提交地址(*可省略*) 'method'=>'post', //提交方法(*可省略默认POST*) 'id' => 'form-save', //设置ID属性 'options' => [ 'class' => 'form-horizontal', //设置class属性 ], 'enableAjaxValidation' => true, 'validationUrl' => 'validate-view', ]); ?> <?php echo $form->field($model,'company_name', ['inputOptions' => ['placeholder'=>'请输入商家名称','class' => 'form-control'], 'template'=>'<label for="inputCompanyName" class="col-sm-1 control-label"><span class="text-red">*</span> 商家名称</label><p class="col-md-8">{input}</p><label class="col-sm-3" for="inputError">{error}</label>'])->textInput()?> <?=Html::submitButton('保存',['class'=>'btn btn-primary']); ?> <?php ActiveForm::end(); ?>
Among them: 'enableAjaxValidation' => true, must be set to tell the form to use ajax Submit
Controller part
The controller is divided into two parts, one part is to verify the correctness of the form, and the other part is to save
1 , Validation part
public function actionValidateView() { $model = new model(); $request = \Yii::$app->getRequest(); if ($request->isPost && $model->load($request->post())) { \Yii::$app->response->format = Response::FORMAT_JSON; return ActiveForm::validate($model); } }
##2. Save part
public function actionSave() { \Yii::$app->response->format = Response::FORMAT_JSON; $params = Yii::$app->request->post(); $model = $this->findModel($params[id]); if (Yii::$app->request->isPost && $model->load($params)) { return ['success' => $model->save()]; } else{ return ['code'=>'error']; } }
$(function(){ $(document).on('beforeSubmit', 'form#form-save', function () { var form = $(this); //返回错误的表单信息 if (form.find('.has-error').length) { return false; } //表单提交 $.ajax({ url : form.attr('action'), type : 'post', data : form.serialize(), success: function (response){ if(response.success){ alert('保存成功'); window.location.reload(); } }, error : function (){ alert('系统错误'); return false; } }); return false; }); });
Yii2 form event Ajax submission implementation method
The above is the detailed content of Yii2 implements ActiveForm ajax submission. For more information, please follow other related articles on the PHP Chinese website!