I have two arrays. One is $categories which contains all categories retrieved from my db and the other is $preSelectedCategories which contains the categories that needs to be pre-selected in my check box list when my form is loaded. I tried to do this:
<?php echo $form->labelEx($model,'category_id'); ?>
<?php echo $form->checkBoxList($model, 'category_id', $categories, $preSelectedCategories, array('multiple'=>true)); ?>
<?php echo $form->error($model,'category_id'); ?>
But I did not succeed. Could anyone help me solve this problem? Thanks!
Edit: I already knew that using CHtml::checkBoxList could help, but what I want here is to use CActiveForm::checkBoxList because I am using a model to validate the checkbox list.
One option would be to use
CHtml::activeNameto get an appropriate name for the input and pass it toCHtml::checkBoxList, like others have suggested.Another option that is, in my opinion, more appropriate would be to add those
category_ids you want pre-checked to the model in the controller, before rendering the form (only when it’s a GET request). Then you wouldn’t need to modify the form at all.