Yii: add custom attributes to CheckBoxes genrated with CHhtml::checkBoxList

June 12, 2011 · Posted in Yii · Comment 

Edit the CHtml.php file (or even better to extend the class), checkBoxList function and replace the loop with the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
 * ZU: modified to include custome attributes for each checkbox item via the htmlOptions =>options property.
 * Works the same as in dropDownList control.
 */
foreach($data as $value=>$label)
{
	//make copy of the original $htmlOptions array
	$optionsCopy = array_merge($htmlOptions);
	///unset the option property from the copy so that it doesn't cause errors in other functions attempting to process the array
	unset ($optionsCopy['options']);
	$checked=!is_array($select) && !strcmp($value,$select) || is_array($select) && in_array($value,$select);
	$checkAll=$checkAll && $checked;
	$optionsCopy['value']=$value;
	$optionsCopy['id']=$baseID.'_'.$id++;
	///if there are any custom attributes set for this checkbox, set them on the copied array
	if ( isset ($htmlOptions['options'], $htmlOptions['options'][ $optionsCopy['value'] ]) ) {
		$custAttrs = $htmlOptions['options'][ $optionsCopy['value'] ];
		foreach ($custAttrs as $attrKey => $attrVal) {
			$optionsCopy[$attrKey] = $attrVal;
		}
	}
	$option=self::checkBox($name,$checked,$optionsCopy);
	$label=self::label($label,$optionsCopy['id'],$labelOptions);
	$items[]=strtr($template,array('{input}'=>$option,'{label}'=>$label));
}
unset ($htmlOptions['options'] );