Problem With Two Models In One Controller

Hi all,

I’m new to Yii Framework and wish to use it to develop a web application.

Currently I’m using Yii 1.1.13 and encountered some problem with two models in one controller

Here, i have to save the data in two different tables, which are get from a form

i have two tables

product_details


user_details

I need to update the text field value "balance" in user_details and "product info" in product_details table by using the same controller.

I refered this http://www.yiiframework.com/forum/index.php/topic/12664-collect-data-for-two-models-in-one-controller/ and updated all the code as same as this method

But, when i click save, only the product info has stored in product_details table. But, the balance doesn’t store in user_details table.

The user_id field is same on both tables.

Hi shathish

Post your code view and the action of controller that saves the models

in _form view file


<?php $form=$this->beginWidget('CActiveForm', array(

	'id'=>'product-form',

	'enableAjaxValidation'=>false,

	'htmlOptions' => array('enctype'=>'multipart/form-data'),

)); ?>

<div class="row">

<?php echo $form->textField($model,'Product_name',array('size'=>50,'maxlength'=>50)); ?>

<?php echo $form->textField(UserDetails::model(),'Balancecredit1',array('id'=>'Balancecredit1','value'=>1); ?>

</div>

Controller


public function actionCreate()

{

$model=new product;

$user=new UserDetails;

// Uncomment the following line if AJAX validation is needed

// $this->performAjaxValidation($model);

if (isset($_POST['product'],$_POST['UserDetails'])) 

{

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

$user->attributes=$_POST['UserDetails'];

if($model->save() && $user->save())

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

here the product name belongs to current model which has been stored

whereas the Balancecredit1 belong to another model doesn’t get stored

firstly, why didn’t use .


..textField($user,...

instead of


...textField(UserDetails::model(),..

?


<div class="row">

<?php echo $form->textField($model,'Product_name',array('size'=>50,'maxlength'=>50)); ?>

<?php echo $form->textField($user,'Balancecredit1',array('id'=>'Balancecredit1','value'=>1); ?>

</div>

Second, did you check the values of $_POST[‘product’] $_POST[‘UserDetails’] after of submit ? for example with var_dump to trace your code

Third,

if the first save succeed may second one doesn’t Is it right for your logic application?

If it is not, you have to use first $model->validate() && $user->validate() before use save


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

$user->attributes=$_POST['UserDetails'];

if($model->validate() && $user->validate() {

$model->save(false);

$user->save(false);

}



Check the above issues, trace your code and tell us what happens :)