[SOLVED] HAS_MANY and dropDownList

I have a table that I need to have a relation back to itself to support a concept where one record "requires" another in the same table. For example purposes the main table is tbl_myRecord and the join table is tbl_myRecordJoin.


CREATE TABLE tbl_myRecord (

  id INT(10) UNSIGNED NOT NULL PRIMARY KEY,

  name VARCHAR(50),

  INDEX (id)

);


CREATE TABLE tbl_myRecordJoin (

  myRecordId INT(10) UNSIGNED NOT NULL,

  myRecordJoinId INT(10),

  INDEX (myRecordId, myRecordJoinId)

);

In the myRecord model I have setup a relation of:


'myRecords' => array(self::HAS_MANY, 'tbl_myRecordJoin', 'tbl_myRecordJoinId'),

I want this to be output on the form as a multi-select box so I have created:


echo $form->dropDownList($model, 'myRecords', CHtml::listData(tbl_myRecord::model()->findAll(), 'id', 'name'), array('multiple'=>'multiple', 'size'=>5));

I have then appropriately modified the controller to save values into tbl_myRecordJoin. The problem is that the saved records do not show up as "selected" when viewing the saved record.

How do I make the saved values show as "selected"?

Thanks,

Jay

As a followup to this what I have discovered is that my original code will submit all the values that were selected but will not show the ones that have been selected.

If I change my code in the view to:


echo CHtml::dropDownList('myRecords', $selectedItems, CHtml::listData(tbl_myRecord::model()->findAll(), 'id', 'name'), array('multiple'=>'multiple', 'size'=>5));

it will show the previously saved values however when I save new values it will only submit one of them in the $_POST variable. $selectedItems is an array that contains the ids of the saved records.

Why are CActiveForm::dropDownList and CHtml::dropDownList implemented differently?

I have solved this by using the following:


echo CHtml::dropDownList('myRecord[fieldName][]', $selectedItems, CHtml::listData(tbl_myRecord::model()->findAll(), 'id', 'name'), array('multiple'=>'multiple', 'size'=>5));

The “myRecord[fieldName][]” can be any string you want, but the “myRecord” should match the name of the model so that “fieldName[]” will become an array within the $_POST[‘myRecord’] array to make processing the selected records easier in the controller.

Hey Kochiro,

Could please share your code from controller file to save this relation.Since i am doing some mistake here. :(