I have two models that I would like to present in a single Yii Controller/View now I know how to make it so that it can Create from both however I resorted to a "hack" for the update side and I would appreciate some help making it right.
I have two models Recipes and RecipeSteps that in defined as a relation in the Recipe controller. RecipeSteps has a column "recipe_id" which is a foreign key and the Primary key of Recipes. Both tables are innoDB and have relations setup. RecipeSteps has ON DELETE CASCADE and ON UPDATE RETAIN set.
This is my actionUpdate from RecipesController.php
public function actionUpdate($id)
{
$model=$this->loadModel($id);
$recipeSteps=$this->loadModelSteps($id);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Recipes']) && isset($_POST['RecipeSteps']))
{
$model->attributes=$_POST['Recipes'];
$recipeSteps->attributes=$_POST['RecipeSteps'];
if($model->save())
$recipeSteps->recipe_id = $model->recipe_id;
$recipeSteps->save();
$this->redirect(array('view','id'=>$model->recipe_id));
}
$this->render('update',array(
'model'=>$model,
'recipeSteps'=>$recipeSteps,
));
}
And this is my loadModel.
public function loadModel($id)
{
$model=Recipes::model()->findByPk($id);
if($model===null)
throw new CHttpException(404,'The requested page does not exist.');
return $model;
}
And here is the second one that I made for the other Model that I would like to condense into a single model.
public function loadModelSteps($id)
{
$recipeSteps=RecipeSteps::model()->findByPk($id);
if($recipeSteps===null)
throw new CHttpException(404,'The requested page does not exist.');
return $recipeSteps;
}
So what I would like to do is figure out how to only have one "LoadModel" that works for both models in actionUpdate.
try this on php 5.3.0 (Class Constants)
public function loadModel($id,$modelName){
$o=call_user_func(array($modelName,'model'));
$model = $o->findByPk($id);
if($modelByPk===null)
throw new CHttpException(404,'The requested page does not exist.');
return $modelByPk;
}