Hey guys, i have a single form for two different models. let’s call the first model “Books” and the second model for “Category”. The primary key in Category is called “bookId” and (funny enough) there’s a relation between the id in Books and bookId in Category (Books id has one Category bookId).
My question is: How to add the same integer number to the two tables when i submit my form from /books/create ?
If I am not mistakes, you’re collecting category name in the single form, as well. so here is the actionCreate
public function actionCreate()
{
$model=new Book;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Book']))
{
$model->attributes=$_POST['Book'];
if($model->save()){
$id=$model->id;
$category=new Category;
$category->bookId=$id;
$category->name=... etc
$this->redirect(array('view','id'=>$model->id));
}
I tried it on my system and I worked. I guess you’re data is not validate, so you can’t save it. Have you checked you database and verify if the main model is saved and the autoincrement id works? If yes, everything should work fine. And yes that was a very long shot
My problem is that i validate both the models at the same time in order for the error-summary to show for both the tables at the same time. It’s therefore not possible for me to do it in exactly the same way as you do.
Perhaps that’s causes the problem. If you have a foreign key in the second model, even if you somehow validate it, because foreign key constrain of the database you end up having problem. And before saving the first model, you won’t be able to access to its autoincrement primary key. You may used a trick to get a maximum id value of the first model and add 1 to it, to get actual id, but it’s not recommended. You may also paste you view, model code here, maybe sb else can help you.