大多数 yii 成员都有同样的问题,所以这里有更甜美的代码和清晰的解释。
首先,您需要找到您预先选择的类别,例如 -
$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'));
现在生成整个类别列表,例如 -
$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');
查看部分 -
<?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'); ?>
试试这个,很好用。。