Hi,
I’ve three tables Post, Product and PostProduct to link the two former tables.
A Post can have 0 or 1 Product, a Product may be in 0 or 1 Post. I obtain this scheme :
Post PostProduct Product
-------- ----------- --------
id 1_____0..1 postId 0..1_____1 id
productId
and these relationships for Post model :
public function relations()
{
return array(
'product'=>array(self::HAS_ONE, 'PostProduct', 'postId'),
);
}
, Product model :
public function relations()
{
return array(
'post'=>array(self::HAS_ONE, 'PostProduct', 'id'),
);
}
and PostProduct model :
public function relations()
{
return array(
'post'=>array(self::BELONGS_TO, 'post', 'postId'),
'product'=>array(self::BELONGS_TO, 'product', 'productId'),
);
}
When I create a Post, I would like to eventually link a Product to it :
<div class="row">
<?php echo CHtml::activeLabel($post,'productId'); ?>
<?php echo CHtml::activeDropDownList($postProduct, 'productId',
CHtml::listData(
$products,
'id',
'name'
)); ?>
</div>
But I fail to save PostProduct. I tried many ways, inspired by the forum, cookbook, or myself, but I got many different error messages.
This is the current actionCreate :
public function actionCreate()
{
$post=new Post;
$postProduct=new PostProduct;
if(isset($_POST['Post'], $_POST['PostProduct']))
{
$post->attributes=$_POST['Post'];
$postProduct->attributes=$_POST['PostProduct'];
$valid=$post->validate();
$valid=$postProduct->validate() && $valid;
if($valid)
{
if(isset($_POST['submitPost']) && $post->save())
{
$postProduct->postId=$post->id;
if($postProduct->save())
$this->redirect(array('show','id'=>$post->id));
}
}
}
$products=new Product;
$criteria=new CDbCriteria;
$criteria->select='id, name';
$criteria->join='inner join PostProduct on Product.id != PostProduct.productId';
$criteria->condition='imageUrl is not null';
$criteria->order="name";
$products=Product::model()->findAll($criteria);
$categories=Category::model()->findAll();
$this->render('create',array(
'post'=>$post,
'categories'=>$categories,
'products'=>$products,
'postProduct'=>$postProduct,
));
}
which raise this error message :
Does anyone has an idea about the way to follow?
Kind regards,
Bruno.