繁体   English   中英

大量分配模型规则

[英]Mass assignment of model rules

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

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

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

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

我实际上是通过一个问题(发现最终的答案https://github.com/yiisoft/yii/issues/987#issuecomment-8886072因此有人提到看在Github上) 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))));
}

现在,这使我可以获取看起来像模型验证规则的数组元素列表,并当场实际将其纳入模型验证规则中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM