1

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?

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

This is definitely what I am wanting but it looks like there is a bug that makes it unusableand the dev isn't pulling in PRs to fix the issue github.com/wbraganca/yii2-dynamicform/pull/89
@kyle ok let me see

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.