Relationship MANY to MANY and activeCheckBoxList

Hi,

I have tables:

  • restaurants (rid, …)

  • restaurant_voucher (rid, vid)

  • vouchers (vid, …)

I created a model for each table.

Model Restaurants.php




	public function relations()

	{

		// NOTE: you may need to adjust the relation name and the related

		// class name for the relations automatically generated below.

		return array(

			'vouchers' => array(self::MANY_MANY, 'Vouchers', 'restaurant_voucher(rid, vid)'),

		);

	}



I edited /views/restaurants/_form.php and added this code




echo CHtml::activeCheckBoxList($model, 'vid', CHtml::listData(Vouchers::model()->findAll(), 'vid', 'name'));



variable $model->vouchers contains all vouchers which belong to a particular restaurant. However, a page /restaurants/update/1 returns a php error ‘Property “Restaurants.vid” is not defined.’.

It makes sence. Restaurants has no vid. How can I create checkboxes using activeCheckBoxList?

I would like display a restaurant with all vouchers which are stored in the table vouchers. Each voucher should be displayed with a label and should be check/unched according to table restaurant_voucher.

  1. Create new property ‘vid’ at Restaurants class

  2. in _form.php use:

//TODO: move below logic to model class or controller class

$vouchers = $model->vouchers;

if (is_array($vouchers ) && count($vouchers))

$model->vid = CHtml::listData($vouchers, ‘vid’,‘vid’);

echo CHtml::activeCheckBoxList($model, ‘vid’, CHtml::listData(Vouchers::model()->findAll(), ‘vid’, ‘name’));

Thank you very much!