how to select multiple checkbox list having many_many relation

i have 3 table:

product

id(pk)

name

brand

id(pk)

price

comment

product_brand

product_id;

brand_id;

pk(product_id,brand_id)

one brand can have many products

so i want a checkboxlist on brand table and when i click on submit data should go into product_brand table

in desired format as shown below.

eg.

brand_id product_id

1 2

1 3

1 5

2 1

2 4

As i’m new to yii so i want a complete explanation for it.

Thanx for any help in advance!

Hi,

first of all you have to declare relations for your product and brand model. Brand can have more product so it HAS_MANY relation.

For easier workin with relations use this extension: http://www.yiiframework.com/extension/cadvancedarbehavior/

After installing this exstension, do the following:

In your brand model:




    public function relations()

    {

        

        return array(

            'products' => array(self::MANY_MANY, 'Product', 'product_brand(brand_id, product_id)'),

            

        );

    }



And your product:




  public function relations()

    {

       

        return array(

            'brands' => array(self::MANY_MANY, 'Brand', 'product_brand( product_id,brand_id)'),

        );

    }



For more about relations please check: http://www.yiiframework.com/doc/guide/1.1/en/database.arr

Then in your view set checkbox:




 <?php

        $data = CHtml::listData(Product::model()->findAll(), 'id', 'name');

        echo CHtml::checkBoxList('NameOfCheckboxList', array_keys(CHtml::listData(Product::model()->findAll(), 'id', 'id')), $data);

        ?>



And to retrieve information about checked products after submiting form in create brand controller:




$productArray = array();

                        if (isset($_POST['NameOfCheckboxList'])) {


                            foreach ($_POST['NameOfCheckboxList'] as $i => $product_model_id) {

                                array_push($productArray , $product_model_id);

                            }

                            //This is name of your relation in brand model

                            $model->products= $productArray ;

                        }



I hope this helps a bit :)

thnx it helped me a lot in understanding the concept

Hi,

If you need to use a Cgridview with checkboxes to create/delete the records in the junction table in a many-many relation, then check out this post.