Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 - ActiveForm ajax submit

How can i use ActiveForm with these requirements?

  • Submit form with ajax.

  • Before submitting with ajax: Check if error exits.

  • After submitting: Display error of field under field's input if the server responses unsuccess saving result.

like image 766
Văn Thái Nguyễn Avatar asked Feb 08 '15 14:02

Văn Thái Nguyễn


1 Answers

This is your form in view. I prefer use different actions for validation and saving. You can join them into single method.

<?php $form = \yii\widgets\ActiveForm::begin([     'id' => 'my-form-id',     'action' => 'save-url',     'enableAjaxValidation' => true,     'validationUrl' => 'validation-rul', ]); ?>  <?= $form->field($model, 'email')->textInput(); ?>  <?= Html::submitButton('Submit'); ?> <?php $form->end(); ?> 

In validation action you should write. It validates your form and returns list of errrs to client. :

public function actionValidate() {     $model = new MyModel();     $request = \Yii::$app->getRequest();     if ($request->isPost && $model->load($request->post())) {         \Yii::$app->response->format = Response::FORMAT_JSON;         return ActiveForm::validate($model);     } } 

And this is save action. In validate input data for security:

public function actionSave() {     $model = new MyModel();     $request = \Yii::$app->getRequest();     if ($request->isPost && $model->load($request->post())) {         \Yii::$app->response->format = Response::FORMAT_JSON;         return ['success' => $model->save()];     }     return $this->renderAjax('registration', [         'model' => $model,     ]); } 

This code will validate your form in actionValidate() and. For submitting your form via AJAX use beforeSubmit event. In your javascript file write:

$(document).on("beforeSubmit", "#my-form-id", function () {     // send data to actionSave by ajax request.     return false; // Cancel form submitting. }); 

That's all.

like image 176
Haru Atari Avatar answered Sep 17 '22 14:09

Haru Atari