Multiple instances of the same model in the same form, Multiple instances of the same model, Two instances of the same model
[...]
```php
public function actionCreate()
{
$model=new User; // User Model
$addressModel_1 = new Address; // Address Model
$addressModel_2 = new Address; // Address Model
if(!empty($_POST))
{
// Set attribute for home address
$addressModel_1->attributes=$_POST['Address'][1];
// Set attribute for
hcom
epany address
$addressModel_2->attributes=$_POST['Address'][2];
// Set attribute for
company addressuser data
$model->attributes=$_POST['User'];
// Set attribute for user data
// Validate all three model
$valid=$addressModel_1->validate();
$valid=$addressModel_2->validate() && $valid;
$valid=$model->validate() && $valid;
if($valid)
{
$addressModel_1->save();
$homeAddressId = $addressModel_1->id;
$addressModel_2->save();
$companyAddressId = $addressModel_2->id;
// Set saved address as user home id
$model->home_address_id = $homeAddressId;
// Set saved address as user
hcom
epany id
$model->company_address_id = $companyAddressId;
// Set saved address as user company id
$model->save();
$this->redirect(array('view','id'=>$model->id));
}
}
$this->render('create',array(
'model'=>$model,
'addressModel_1'=>$addressModel_1,
'addressModel_2'=>$addressModel_2,
));
}
```[...]
```php
public function actionUpdate($id)
{
{
// Load user data in model
$model=User::model()->findByPk($id);
// Load
useraddress data in
maddressModel
_1
$addressModel_1=Address::model()->findByPk($model->home_address_id);
// Load address data in addressModel_
1 2
$addressModel_2=Address::model()->findByPk($model->company_address_id);
// Load address data in addressModel_2
if(!empty($_POST))
{
// Set attribute for home address
$addressModel_1->attributes=$_POST['Address'][1];
// Set attribute for
hcom
epany address
$addressModel_2->attributes=$_POST['Address'][2];
// Set attribute for
company addressuser data
$model->attributes=$_POST['User'];
// Set attribute for user data
// Validate all three model
$valid=$addressModel_1->validate();
$valid=$addressModel_2->validate() && $valid;
$valid=$model->validate() && $valid;
if($valid)
{
$addressModel_1->save();
$addressModel_2->save();
$model->save();
}
}
$this->render('update',array(
'model'=>$model,
'addressModel_1'=>$addressModel_1,
'addressModel_2'=>$addressModel_2,
));
}
```
### View Form
For create and update same page r
aender as _form,
**from below view code you can get
the idea
on how
ito pass model
s and set attribute name
s for elements..**
```php
<div class="form">[...]
### Demo
The demo some what look
s like,
<img src="http://i1147.photobucket.com/albums/o556/master753951/multiple_instance_demo.png" alt="All field validation" width="600" />
**
There will beFor every single entry in User table
andthere will be two entry in Address table (
for home and company
) same data update on update scenario).**
I hope this will help to many...