SOLVED - Please refer to http://code.google.c…s/detail?id=217 which fixes the same issue with activeListBox and the same fix can easily be adapted to activeCheckBoxList…
Thanks scythah!
I have searched around the forum and found a few references to the following problem, but I will outline it in more detail as it relates to what I'm trying to . Basically activeCheckBoxList is not automatically checking checkboxes for a MANY_MANY relationship.
I have these two tables:
Topic Region
and they have a N:N in table:
TopicRegion
Topic model has this relationship:
'regions'=>array(self::MANY_MANY, 'Region', 'TopicRegion(topicId, regionId)'),
Then I'm outputting an activeCheckBoxList in the _form view for Topic:
CHtml::activeCheckBoxList($model, 'regions', CHtml::listData(Region::model()->findAll(), 'id', 'title'));
The activeCheckBoxList is outputting checkboxes for each Region as expected. However if assign a few regions to a topic there is a problem with it automatically selecting the related regions.
I have these relationships:
[table]
[tr]
[td]Topic ID[/td]
[td]Topic[/td]
[td]Region ID[/td]
[td]Region[/td]
[/tr]
[tr]
[td]
[td]Accommodation[/td]
[td]
[td]Gold Coast[/td]
[/tr]
[tr]
[td]
[td]Accommodation[/td]
[td]
[td]Brisbane[/td]
[/tr]
[/table]
ie. the TopicRegion table has:
[table]
[tr]
[td]Topic ID[/td]
[td]Region ID[/td]
[/tr]
[tr]
[td]1[/td]
[td]1[/td]
[/tr]
[tr]
[td]1[/td]
[td]2[/td]
[/tr]
[/table]
But activeCheckBoxList doesn’t check the checkboxes correctly. It will always check the first checkbox and none of the others if there is any related Region found.
Somehow I think it is related to CHtml::checkBoxList method for search for the value in the attribute object: eg.
web/helpers/CHtml.php:733
$checked=!is_array($select) && !strcmp($value,$select) || is_array($select) && in_array($value,$select);
So in this case $select will the the model’s region object (included below), and the test is going to be
in_array($value,$select).
But for whatever reason, in_array is always returning true for the first relationship (region with id 1), ie
in_array(‘1’, $select), and false for any search after that, ie.
in_array(‘2’, $select). So perhaps it’s related to the details of how in_array performs the search? Same with if I do
array_search(‘1’, $select)it always return the key 0, but
array_search(‘2’, $select)finds no key.
array dump of the $select object (which is the related regions) is below in a reply coz I couldn't fit it in this post… You can see both Regions are in there…