简体   繁体   English

大量分配模型规则

[英]Mass assignment of model rules

I want to know if there is a easy way to mass assign a new set of rules for a model. 我想知道是否有一种简单的方法可以为模型批量分配一组新规则。

The use case is that I could have a validator rule which contains a set of sub rules for a specific model. 用例是我可以有一个验证器规则,其中包含一组特定模型的子规则。 I want to dynamically load that model, assign its attributes (both of which I know how to do) and then mass assign the set of rules. 我想动态加载该模型,分配其属性(我都知道如何做),然后批量分配规则集。 The rules will look like: 规则如下所示:

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

I know I can do this by picking out the classes individually and building up the validators manually but is there any easy way to just tell a Yii model to reload the validators with this specification? 我知道我可以通过单独选择类并手动建立验证器来做到这一点,但是有什么简单的方法可以告诉Yii模型使用此规范重新加载验证器?

I actually found out the answer in the end through a issue ( https://github.com/yiisoft/yii/issues/987#issuecomment-8886072 ) on Github whereby it was mentioned to look at the CModel validatorList . 我实际上是通过一个问题(发现最终的答案https://github.com/yiisoft/yii/issues/987#issuecomment-8886072因此有人提到看在Github上) CModel validatorList After browsing this source code for a while I came up with the following piece of code, mostly ripped from CModel itself: 浏览此源代码一段时间后,我想到了以下代码,这些代码大部分是从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))));
}

Now this allows me to take a list of array elements that look like validation rules for a model and on the spot actually make them into validation rules for the model. 现在,这使我可以获取看起来像模型验证规则的数组元素列表,并当场实际将其纳入模型验证规则中。

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

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