How to update more Model in one Controller

Hi all,

I want to ask How to update more Model in one Controller?I can create new follow http://www.yiiframework.com/wiki/19/how-to-use-a-single-form-to-collect-data-for-two-or-more-models.But Dont know how to do for edit and update.

1.I insert 3 tables.customer,contact,creditCard,after insert contact and creditcard,I get id just inserted and assign FK in customer table,and insert DB.Everything Ok.And now how to update?When I click edit button get error.

My code:

if(isset($_POST[‘Customer’],$_POST[‘Contact’],$_POST[‘CreditCard’]))

	{


		$model->attributes=$_POST['Customer'];


		$contact->attributes = $_POST['Contact'];


		$card->attributes = $_POST['CreditCard'];


		


		$valid = $contact->validate();


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


		


		$transaction = Yii::app()->db->beginTransaction();


		try{


			if($valid){


				if($contact->save(false) && $card->save(false)){


					$model->contact_id = $contact->id;


					$model->credit_card_id = $card->id;


					if($model->save()){


						$transaction->commit();


						$this->redirect(array('view','id'=>$model->id));


					}


				}


			}


		}catch (Exception $e){


			$transaction->rollback();


			Yii::log('Exception when saving data: ' .$e->getMessage(), CLogger::LEVEL_ERROR);


		}


		


	}





	$this->render('create',array(


		'model'=>$model,


		'contact'=>$contact,


		'card'=>$card,	


	));

code in function actionCreate().

Sorry my English not good.Hope you got my idea.

Thanks,

Duke

Hi Loi Tran,

Welcome to the forum!

What error do you get?

About updating, you have to load the model instances before you show them in a form.

Your actionUpdate() should be something like the following:




$model = $this->loadModel($id);

$contact = $model->contact;

$card = $model->creditCard;


if(isset($_POST['Customer'],$_POST['Contact'],$_POST['CreditCard']))

{

	$model->attributes=$_POST['Customer'];

	$contact->attributes = $_POST['Contact'];

	$card->attributes = $_POST['CreditCard'];

			

	$valid = $contact->validate();

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

			

	$transaction = Yii::app()->db->beginTransaction();

	try{

		if($valid){

			if($contact->save(false) && $card->save(false)){

//				$model->contact_id = $contact->id;

//				$model->credit_card_id = $card->id;

				if($model->save()){

					$transaction->commit();

					$this->redirect(array('view','id'=>$model->id));

				}

			}

		}

	}catch (Exception $e){

		$transaction->rollback();

		Yii::log('Exception when saving data: ' .$e->getMessage(), CLogger::LEVEL_ERROR);

	}

		

}


$this->render('update',array(

	'model'=>$model,

	'contact'=>$contact,

	'card'=>$card,	

));



In the above, I assume you have established ‘contact’ and ‘creditCard’ relations for Customer.

So I didn’t explicitly load them.

And in updating, you don’t need to set PK->FK relations any more for the existing instances.

[EDIT]

BTW, please use “code” markup when you post. :)