How To Display Multiple Checkbox List And Store In Database In Yii

I have 3 Models in Yii -

[list=1]

[*]Brand

[*]Product

[*]BrandProduct

[/list]

Database details -


Brand -


id (pk)

name

Product -


id (pk)

name

price

description

BrandProduct -


id (pk)

prod_id (fk)

brand_id (fk)

Note - One product has many brand.

  1. How to display the Brand list in the Listbox (with CheckBox) on product page, when i’m enter the product???

  2. Also how to save multiple brand with single product in BrandProduct db???

Please help me to resolve my issue, thanks in advance!!

use listCheckBox widget to show Brand list.

To accept values from listCheckBox in server side, add new member (for instant brands, it will be array) to Product model.

You can add validation to check brands array for correct (exist values from Brand table) values.

After successfully saving product model, save manually values to BrandProduct table.

Hope, it was undestandable explanation.

Good luck.

Thanks for your help. now i have done through - listData & checkBoxList


$list = CHtml::listData(Brand::model()->findAll(array('order' => 'name')), 'id', 'name');

echo CHtml::checkBoxList("BrandProduct[prod_id][]", "", $list);

Tell me how can i store in BrandProduct database???




public function actionCreate()

  {

	$model = new Product;

	$brands = array();


	if(isset($_POST['Product']))

	  {

	    $model->attributes=$_POST['Product'];	

	    $valid=$model->validate();


	    foreach ($_POST['BrandProduct'] as $key => $brandprod)

		{

		  $brandproduct = new BrandProduct;

		  $brandproduct->attributes = $brandprod;

		  $valid = $brandproduct->validate() && $valid;

		  $brands[$key] = $brandproduct;

		}

				


	if ($valid)

          {

            if ($model->save())

               {

                   foreach ($brands as $brandproduct)

                      {

                        $brandproduct->save();

                      }

                }

						

  $this->redirect(array('product/index','msg'=>'success'));

       }


  }

		

  $this->render('create',array(

      'model'=>$model,

   ));

}



dump data -


array(3) { 

	["Product"]=> array(6) 

		{ ["name"]=> string(9) "Ice Cream"

		  ["price"]=> string(3) "100"

		  ["description"]=> string(9) "Ice Cream"

		} 

	["BrandProduct"]=> array(1) 

	    { ["brand_id"]=> array(2) 

		    { [0]=> string(1) "2"

			  [1]=> string(1) "1"

			}

		} 

 ["yt0"]=> string(6) "Create" }

Getting error like - Invalid argument supplied for foreach()

Error in which foreach(). First place I’d look. Also what happens in update, when the nothing changes in the brand list?

Just had a thought: You may only get back a one dimensional array for your checkBoxList so $key=>$value won’t work. You could set $brands = explode($_POST[‘BrandProduct’],’,’);