K
K
kirillantv2017-09-12 15:52:56
Yii
kirillantv, 2017-09-12 15:52:56

How to implement multiple sequential forms in yii2 via AJAX?

Good afternoon, ladies and gentlemen. Need daddy's advice. I have Yii2 and an object (for example, a product), whose data (categories, attributes) are written to different database tables. For each database table I want to make a separate form, each of which cannot be accessed without validating the previous one.
So. The question is how to organize all this in the most orthodox way, so that the forms switch one after another using AJAX. I see two possible ways:
1. Implement everything in one controller, and do the validation using

$form = ActiveForm::begin([
    'id' => $model->formName(),
    'enableAjaxValidation' => true,
    'validationUrl' => Url::toRoute(['items/validation'])

And deny access to the next section through js.
2. Either load each subsequent page using $this->renderAjax. However, it turns out that in this case it is necessary to store already filled data somewhere? For example, in cookies.

PS I will be extremely glad to see examples of this kind of implementations on yii2. But more interested in the right approach.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Maxim Fedorov, 2017-09-12
@kirillantv

use some form wizard for this, for example this one or look towards this js plugin

D
Denis A., 2017-09-12
@myphpscript

Alternatively, you can create a class (from yii\base\Model) with all the necessary fields, make a script with validation rules for each step. In the controller, we specify the desired scenario, we check if ok we save the model to the session and display the following form. Following. step we take the form from the session and do the same. You can easily return to the previous step, the data entered earlier will be loaded. On the last one, we do $model->save(), in which we save the data to all the necessary tables. It will not be superfluous to wrap it in a transaction.

A
Alexander N++, 2017-09-12
@sanchezzzhak

the simplest option is PJAX
Do everything the same as without ajax display
form 1
send form 1
display the result as a form if an error then show form 1 and so on.
In the right place between the form, put
Pjax::begin
form
Pjax::end

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question