我无法使用选项正确验证checkBoxList:
这是config
形式的元素'benefits' => array(
'type' => 'checkboxlist',
'items' => \application\models\db\Option::items('application.benefits'),
),
这将从options表中提取选项并相应地填充checkBoxList。
它在HTML中填充得很好,当我尝试验证表单时,我遇到问题......
Yii返回的实际验证错误是: 好处必须是1或0。
验证的代码如下:
array('benefits', 'boolean'),
所以问题是,如何根据数据库中已有的选项验证checkBoxList?
编辑:找到解决方案
以下解决方案是我的规则,用于检查已检查项目的选项复选框。参数是:
'category' => 'category.table'
规则如下(这将使用其他规则的表单模型:
public function checkboxlistoptions($attribute, $params)
{
$options = \application\models\db\Option::model()->items($params['category']);
if(is_array($options) && is_array($this->$attribute)){
foreach($this->$attribute as $item){
$match = false;
foreach($options as $optionID => $option)
if($item == $optionID) $match = true;
if(!$match) $this->addError($attribute, 'Could not match option to item');
}
} else {
$this->addError($attribute, 'Could not find options');
}
}
该规则适用如下:
array('attributeName', 'checkboxlistoptions', 'category' => 'category.table'),
希望这会有所帮助:)