My modification on CHtml::activeCheckBoxList()

The goal is to do something like this. For example, Post and Tag are in a MANY_MANY relationship, i.e., in Post model class, we have


'tags' => array(self::MANY_MANY, 'Tag',  'posts_to_tags(post_id, tag_id)')

Then it should be able to generate HTML checkbox list for adding/removing tags for a post like this:


echo CHtml::activeCheckBoxList($postModel, 'tags',  $tagsData);

where


$tagsData = CHtml::listData(Tag::model()->findAll(), 'tag_id',  'tag_name');

So I modified CHtml::activeCheckBoxList() as follow:




public static function activeCheckBoxList($model,$attribute,$data,$htmlOptions=array())

{

    self::resolveNameID($model,$attribute,$htmlOptions);


    // Remove this line of code

//  $selection=self::resolveValue($model,$attribute);


    // Add the following code in order to support MANY_MANY relationships

    $relations = $model->relations();

    if (isset($model[$attribute][0]) && $model[$attribute][0] instanceof CActiveRecord && $relations[$attribute][0] == CActiveRecord::MANY_MANY) {

        // extract 'foreignField' from 'relationTable(thisField, foreignField)'

        $foreignField = preg_replace('/^.+\(.+\s*,\s*(.+)\)$/s', '$1', $relations[$attribute][2]);

        $selection = array();

        foreach ($model->$attribute as $attr) {

            $selection[] = $attr->$foreignField;

        }

    } else {

        $selection = self::resolveValue($model,$attribute);

    }


    // The following code does not get changed

    if($model->hasErrors($attribute))

        self::addErrorCss($htmlOptions);

    $name=$htmlOptions['name'];

    unset($htmlOptions['name']);


    $hiddenOptions=isset($htmlOptions['id']) ? array('id'=>self::ID_PREFIX.$htmlOptions['id']) : array();

    return self::hiddenField($name,'',$hiddenOptions)

        . self::checkBoxList($name,$selection,$data,$htmlOptions);

}



I am new to Yii. Can anybody help me to find problems in the code?

Just ran into a bug. Have edited this post.

thx