Answer the question
In order to leave comments, you need to log in
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'])
Answer the question
In order to leave comments, you need to log in
use some form wizard for this, for example this one or look towards this js plugin
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.
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 questionAsk a Question
731 491 924 answers to any question