Adding Data To Multiple Tables From A Single Form

hi.

I have two tables student and user . From the students form I wish to send some data to student table and some to user table .

In studentController my code is

public function actionCreate()

{


	$model=new Student;


            $model2=new User;





	if(isset($_POST['Student']))


	{


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


                   


		if($model->save())


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


                    


                    $model2->attributes=$_POST['User'];			


                    


                    if($model2->save())


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


                          }





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


                                   'model'=>$model,


                                   'model2'=>$model2,


                           ));


                   }

In student.php my code is

public function rules()


{


	// NOTE: you should only define rules for those attributes that


	// will receive user inputs.


	return array(


                    array('fName', 'length', 'max'=>250),


		array('name, email', 'length', 'max'=>50),


		array('nic', 'length', 'max'=>10),


                array('user_id', 'length', 'max'=>20),


                //array('user_id', 'safe'),


		// The following rule is used by search().


		// @todo Please remove those attributes that should not be searched.


		array('id, name, nic,fName, email', 'safe', 'on'=>'search'),


	);


}

[b]In _form.php my code is

[/b]

<?php echo $form->errorSummary($model,$model2); ?>

&lt;div class=&quot;row&quot;&gt;


	&lt;?php echo &#036;form-&gt;labelEx(&#036;model,'email'); ?&gt;


	&lt;?php echo &#036;form-&gt;textField(&#036;model,'email',array('size'=&gt;50,'maxlength'=&gt;50)); ?&gt;


	&lt;?php echo &#036;form-&gt;error(&#036;model,'email'); ?&gt;


&lt;/div&gt;

<div class="row">

	&lt;?php echo &#036;form-&gt;labelEx(&#036;model2,'user_id'); ?&gt;


	&lt;?php echo &#036;form-&gt;textField(&#036;model2,'user_id',array('size'=&gt;20,'maxlength'=&gt;20)); ?&gt;


	&lt;?php echo &#036;form-&gt;error(&#036;model2,'user_id'); ?&gt;


&lt;/div&gt;

after exectuion I get the error

[i]

Property "Student.user_id" is not defined. [/i]

i dont understand why???

rules for attribute ‘user_id’ need to define in user.php not in student.php

$model2 is User model instance and user_id is User model attribute and you wrote the validation rule of user_id in student.php

thanks rahul

but now i get the error

Undefined variable: model

Resolved…