0

我想知道是否有一种简单的方法可以为模型批量分配一组新规则。

用例是我可以有一个验证器规则,其中包含一组特定模型的子规则。我想动态加载该模型,分配其属性(我都知道如何做),然后批量分配规则集。规则将如下所示:

'rules' => array(
    array('road', 'string'),
    array('town', 'string'),
    array('county', 'string'),
    array('post_code', 'string'),
    array('telephone', 'integer')
)

我知道我可以通过单独挑选类并手动构建验证器来做到这一点,但是有没有简单的方法来告诉 Yii 模型用这个规范重新加载验证器?

4

1 回答 1

0

实际上,我最终通过 Github 上的一个问题( https://github.com/yiisoft/yii/issues/987#issuecomment-8886072 )找到了答案,其中提到了查看CModel validatorList. 在浏览了这个源代码一段时间后,我想出了以下一段代码,大部分是从CModel它自己身上撕下来的:

$c=new EMongoModel();
foreach($this->rules as $rule){
    if(isset($rule[0],$rule[1]))  // attributes, validator name
        $c->validatorList->add->add(CValidator::createValidator($rule[1],$this,$rule[0],array_slice($rule,2)));
    else
        throw new CException(Yii::t('yii','{class} has an invalid validation rule. The rule must specify attributes to be validated and the validator name.',
                    array('{class}'=>get_class($this))));
}

现在,这允许我获取一个看起来像模型验证规则的数组元素列表,并在现场实际将它们变成模型的验证规则。

于 2013-02-18T16:06:11.770 回答