Add Dinamically Instances Of A Model In A Form

Hi I’m new using Yii and I’m having a problem, I have two models, modelA and modelB , modelB has a foreing key to modelA, so what I want is in the form of modelA add instances of modelB dinamically. I mean in the form of modelA fill all the fields of modelA and add 3 or 4 instances of modelB, then submit everithing together. There is any way to do it with yii?

Please an example would be helpful

Something like this?

Yes, but that example is for update, but for add I don’t know how many instances will be created, so I don’t know how to create the form when I don’t know how many would be cause I can’t do the foreach if initially the array is empty, maybe I’m missing something.

This depends on how complicated the form for ModelB is.

If it’s a simple textbox, I’d use JS so the user can add/remove textboxes. Your view should name the textboxes so that your controller can loop over the values as an array - see here.

If your ModelBs are more complicated I would make the user fill out a regular ModelB form with a drop down of ModelAs they can associate it with.

you can do some modification to the code and use for your create method

This worked for me:

$a = new A;

$b = new B;



            $valid=$b->validate() && $valid; 






                    $b->order_id = $a->id;