kyle
kyle

Reputation: 2638

Create multiple model via ActiveForm Yii2

I have a form in my Yii2 project and I need to allow for multiple models to be created using it. Overall I have a single Group and multiple Person ActiveRecords that will be created using the form, and each Person record will belong to the Group.

For example I have this class that is the form:

<?php namespace app\models\forms;

class GroupForm extends yii\base\Model {
    public $name;
    public $description;
    public $date;
    public $people = [];

    ....
}

And visually it will be something similar to this:

enter image description here

I want to be able to use the plus and minus buttons to add additional people to the form. I have the JS in place to actually handle the HTML cloning and such, but I am not sure about how to create the first Person.

I know that I will need the name to be something like Person[0][first_name] but when I instantiate the GroupForm there are no people objects created yet (saved or in memory) so I can't do something like <?php echo $form->field($model->people[0], 'first_name')->textInput(); ?>.

Once the form was submitted I planned on then iterating over all of the 'People' fields in the POST data and loading that into new People objects.

Is it possible to do this with the ActiveForm or is the answer to just not use the ActiveForm and create the inputs using the Html class in Yii and then using JS to change the person index?

Upvotes: 1

Views: 2575

Answers (1)

Kiran Muralee
Kiran Muralee

Reputation: 2060

Basically what I understood from your post is you need to use dynamic form in your Yii2 project. In your case the form should be containing the group information plus multiple persons to be created along with it. In Yii2 this functionality can be implemented through the usage of wbraganca/yii2-dynamicform form widget.There is very good documentation to how to use the widget with an example scenario.The widget documentation can be found at

https://github.com/wbraganca/yii2-dynamicform

More information and working demos at

http://wbraganca.com/yii2extensions/dynamicform-demo1/create

Hope this helps

Upvotes: 1

Related Questions