Yii2 - ActiveForm ajax submit

Văn Thái Nguyễn picture Văn Thái Nguyễn · Feb 8, 2015 · Viewed 51.8k times · Source

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.

Answer

Haru Atari picture Haru Atari · Sep 3, 2015

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.