I have to update two tables from one form. I have two tables TestA and TestB. So how can I update two tables where TestB.testid=TestA.testid. Both the tables are populated. I need to update TestB based on the id of TestA. Below is the actionUpdate of TestA.
public function actionUpdate($id)
{ $model_A=new TestA;
$model_B=new TestB;
$model=$this->loadModel($id);
if(isset($_POST['TestA'])&&isset($_POST['TestB']))
{
$model_A->attributes=$_POST['TestA'];
$model_B->attributes=$_POST['TestB'];
$model_B->name="test";
$model_A->save();
$model_B->save();
$this->render('update',array(
'model'=>$model,
));
}
When I run the application, a new entry is created in TestB instead of updating the existing one. How can I pass the id to update the row in table TestB
Add a hidden field in the form with the id of the second model and extract it from POST to load it, just like the first one using id passed in action parameter.
You said TestB is an existing entry. But where do you load it? It looks as if you only create a new TestB entry and then save it. You never load it > update it > and then save it.
public function actionUpdate($id)
{
//load A by id
$model_A=$this->loadModel($id);
//find B by $testid from A id
$model_B=$this->loadModelB($model_A->testid);
if(isset($_POST['TestA'])&&isset($_POST['TestB']))
{
$model_A->attributes=$_POST['TestA'];
$model_B->attributes=$_POST['TestB'];
$model_B->name="test";
$model_A->save();
$model_B->save();
}
$this->render('update',array(
'modelA'=>$model_A,
'modelB'=>$model_B,
));
}