checkBoxList checked by default


This is My view:


echo $form->checkBoxList(

        $model, 'originalFileCalendars', CHtml::listData(OriginalFile::model()->getCalendarType(), 'ct_id', 'type_name')



How I can get checked checkboxes if their values IN the array $calendar.

Please Help Thank you

Since checkBoxList creates an array of checkboxes, your $model->originalFileCalendars property has to contain an array with your selected/checked values. For example, doing something like:

$model->originalFileCalendars = array(1, 2);

echo $form->checkBoxList($model, 'originalFileCalendars', CHtml::listData(OriginalFile::model()->getCalendarType(), 'ct_id', 'type_name'));

Should show checkboxes with values 1 and 2 checked, if they exist and are returned your getCalendarType() method.

Most of yii members having same issue, so here more sweet code with clear explanation. eg. - Categories

First you need to find your pre-selected categories like -

$criteria = new CDbCriteria();

$criteria->select = 'category_id as id';

$criteria->condition = 'userid = :userid';

$criteria->params = array(':userid' => Yii::app()->user->id);

//store pre-selected id into variable  - $selected_keys

$selected_keys = array_keys(CHtml::listData(MyCategory::model()->findAll($criteria), 'id', 'id'));

Now generate whole category list, like -

$list = CHtml::listData(Categories::model()->findAll(array('order'=>'id')), 'id', 'category_name');

//htmlOptions for class and others elements

$htmlOptions = array('template' => '{input}{label}', 'separator'=>'', 'class'=>'in-checkbox', 'multiple'=>true, 'checked'=>'checked');

View part -

<?php echo $form->labelEx($model, 'Category', array('class'=>'col-md-3 control-label')); ?>

<?php $model->Category = $selected_keys; //assign pre-selected list to Category list

      echo $form->checkBoxList($model, 'Category', $list, $htmlOptions); ?>

<?php echo $form->error($model, 'Category'); ?>

Try this, work great…