Multiple instances of the same model in the same form

Hello, my first time starting a thread here :)

I was wondering if you could help me here, in my controler I have something like this:




$model1 = new Contact;

$model2 = new Contact;

$model3 = new Contact;



This 3 contacts are rendered in the same form, but since Yii uses the class name for the input name and id, the post does not contain expected data. I tried making inherited clases out of Contact but that only works when creating a new instance not while loading an old one (for some reason). Also the 3 clases have a lot of fields so I find setting the name and id manually is not an option.

How can I say the form to use a different prefix for each of the 3 models? You can assume my form is just as created by gii, $form=$this->beginWidget(‘CActiveForm’,…);

Thank you!

Heh… I found my own answer just after starting the topic… I’m sorry…

I’m leaving this here for future generations:

gii’s generated models take a sole parameter, the class name they belog to, so first you must create inherited dummy classes:




class Contact1 extends Contact {}

class Contact2 extends Contact {}

class Contact3 extends Contact {}



Either in their own (Contact1.php, etc) files or at the top of the controller file before the controller class declaration.

Then you can create the models this way:




$model1 = new Contact("Contact1");

$model2 = new Contact("Contact2");

$model3 = new Contact("Contact3");



Or you can load them:




$model1 = Contact::model("Contact1")->findByPk($model1pk);

$model2 = Contact::model("Contact2")->findByPk($model2pk);

$model3 = Contact::model("Contact3")->findByPk($model3pk);



Sorry once again for self answering, if this is against the rules please delete the thread.

While this may work, its far from being the best solution.

Check this topic:

http://www.yiiframework.com/doc/guide/1.1/en/form.table