Multiple forms for a single model

Hello.

I’m trying to solve this for a couple of days already and still can’t find a proper solution, please help me someone :unsure:

I got a new project with a how-to section. In this section there’re step-by-step articles about making stuff. The thing is, when user is adding a new article the number os steps is not a constant and the form for each step is generated by js after user press “Add step” button.

Each step have it’s own enty in database (with foreighn key set to article’s id) and so the model is set for step and for the article. I have no problem with the article form, but I can’t figure out how to hadle multiple forms for the same StepModel.

What is the problem in handling multiple forms?

Thank you for your response.

The thing is, that I declare Model in Controller like this:


$post = new PostRecord();

and sending it into the view:


$form = new ActiveForm::begin([...]);

$form->field($post, 'title');

...

$form-end();

and there could be 1,2,3…N forms like this, but only one Model was declared in Controller.

I need to save all forms at once, and I can’t find a proper way to do it.

In your controller:




public function actionForm()

{

     $arrModels = array();

     for($k=0;$k<NUM_RECORD;$k++)

     {

          $model = new Model();

          $arrModels[] = $model;

     }


     $this->render('form', array('arrModels' => $arrModels) );

}



In your view:




$form = new ActiveForm::begin([...]);


for($k=0;$k<sizeof($arrModels);$k++)

{

     $model = $arrModels[$k];

	$form->field($model, '[0]title');

	...

	

	$form->field($model, '[1]title');

	...

	

	

	$form->field($model, '[n]title');

	...

}


$form-end();



prepend at attribute index of model.

Then in your controller you have to put code to handle data from $_POST.

The thing is NUM_RECORD is not the same every time. It’s have to be defined by user by adding/removing steps

No problem. You can pass to Controller’s action a parameter to identify number of model to be instanced.

Sorry, I must be not understanding something :unsure:

How can I tell Controller to increase amount of models in a view without reloading page and keep the data that user already filled inputs with…

User can add new model during compiling form?

Or number of models is established when you enter in form action?

This.

I found a solution, may be temporary, is to create a separete Form Model and a Controller action to generate and handle it via AJAX. It seems to work as it should, but I still think there’s a better way.