Hi all, I am new to Yii Framework and now, I am facing a problem of updating details for two tables from one submitted form. I have two tables of User and Student. I wish to update the username from the submitted form (Student table) and update the User table as well. Previously, I have updated the Student table successfully but not the User table. How to update both table at the same time? I follow the link here example but it does not works to me. Please help me~ Thanks in advance.
** id (student table) = id_num (user table) **
Here’s my database:
[color="#FF0000"]User table[/color]
id | id_num | user type | username | password |
…
10 | 12 | student | aaa | 123 |
[color="#FF0000"]Student table[/color]
id | username | password |
…
12 | aaa | 123 |
Here’s my code:
[color="#FF0000"]controller:[/color]
public function actionUpdate($id)
{
$model=$this->loadModel($id);
$model2=$this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Student']) && isset($_POST['User']))
{
$model->attributes=$_POST['Student'];
$model2->attributes=$_POST['User'];
$model2->username = $model->username;
$model->save();
$model2->save();
$uploadedFile=CUploadedFile::getInstance($model,'foto');
if(is_object($uploadedFile) && get_class($uploadedFile)==='CUploadedFile') // check if uploaded file is set or not
{
$model->foto = $uploadedFile;
}
if($model->save())
{
if(is_object($uploadedFile))
{
$model->foto->saveAs(Yii::app()->basePath.'/../images/'.$model->foto);
}
$this->redirect(array('view','id'=>$model->id));
}
}
$this->render('update',array(
'model'=>$model,
'model2'=>$model2,
));
}
[color="#FF0000"]model[/color]
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('foto, username, password, programme, intake, email, contact', 'required'),
array('contact', 'numerical', 'integerOnly'=>true),
array('username', 'length', 'max'=>10),
array('password, programme, intake', 'length', 'max'=>30),
array('email', 'length', 'max'=>50),
array('foto', 'length', 'max'=>255, 'on'=>'insert,update'),
array('foto', 'file','types'=>'jpg, gif, png', 'allowEmpty'=>true, 'on'=>'update'),
// The following rule is used by search().
// @todo Please remove those attributes that should not be searched.
array('id, username, password, programme, intake, email, contact', 'safe', 'on'=>'search'),
);
}