This article is mainly for you to introduce the YII2 implementation of ActiveForm AJAX submissions of relevant information, with a certain reference value, interested in small partners can refer to
Do the project will always encounter the function of Ajax submission, especially in the background to submit, the general will use the model automatically generated, the use of this function is more frequent, in fact, as long as the understanding of the process, operation is very simple, easy to use.
Form section
<?php $form = Activeform::begin ([' action ' = = [' Save '],//Submit address (* May omit * ) ' method ' = ' post ', //Submit Method ( * can omit default post*) ' id ' = ' form-save ',//Set id attribute ' options ' = [ ' class ' = ' form-horizontal ',// Set the Class property ], ' enableajaxvalidation ' = = True, ' validationurl ' = ' Validate-view ',]);?> <?php echo $form->field ($model, ' company_name ', [' inputoptions ' + = ' placeholder ' = ' Please enter the merchant name ', ' class ' = > ' Form-control ', ' template ' = ' <label for= ' inputcompanyname ' class= ' col-sm-1 control-label ' ><span class= "text-red" >*</span> Merchant name </label><p class= "col-md-8" >{input}</p><label class= " Col-sm-3 "for=" Inputerror ">{error}</label>"])->textinput ()?> <?=html::submitbutton (' Save ', [' class ' = ' btn btn-primary ']); ?> <?php activeform::end ();?>
Where: ' enableajaxvalidation ' = = True, must be set, tell table with Ajax commit only
Controller section
The controller is divided into two parts, part is the correctness of the validation form, and the other part is to save
1, the 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 '];} }
Ajax Submit from Form
$ (function () {$ (document). On (' Beforesubmit ', ' Form#form-save ', function ()} { var form = $ (this); Returns the wrong form information if (Form.find ('. Has-error '). Length) { return false; } Form submission $.ajax ({ URL : form.attr (' action '), type : ' Post ', data : Form.serialize () , success:function (response) { if (response.success) { alert (' Save succeeded '); Window.location.reload (); } }, error:function () { alert (' System error '); return false; } }); return false; }); });
Special attention I use is Yii2 adminlte frame backstage, concrete operation process test project, basic operation process are the same.