2013-02-18 83 views
0

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

用例是我可以有一个验证器规则,它包含一组特定模型的子规则。我想动态加载该模型,分配其属性(我知道该怎么做),然后批量分配一组规则。规则将类似于:

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

我知道我可以通过单独挑出类和手工,但建立验证程序做到这一点是有没有简单的方法来只是告诉Yii的模型与该说明书重新加载验证?

+0

使用场景? http://www.yiiframework.com/wiki/266/understanding-scenarios/ http://www.yiiframework.com/forum/index.php/topic/21730-scenario-and-find-or-findall/ – 2013-02-18 13:31:03

+0

@ ImreL如何?我不确定这有多大帮助,我正在寻找将质量规则分配给模型不包含某些场景的某些规则 – Sammaye 2013-02-18 13:44:36

+0

目前尚不清楚您的质量分配意味着什么。是将规则分配给模型的集合(数组)还是关于将一​​个模型的多个规则分配给一个赋值?前者不存在任何特定的性能(您仍然需要遍历每个模型或使用sublcassing等)。对于最后一个使用场景,根据您的需求是很多选项之一 – 2013-02-18 14:00:10

回答

0

我在Github上通过一个问题(https://github.com/yiisoft/yii/issues/987#issuecomment-8886072)最终找到了答案,据此提到查看CModelvalidatorList。浏览此源代码一段时间后,我想出了下面的一段代码,大多来自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)))); 
} 

现在,这可以让我去,看起来像验证规则的模型数组元素的列表并在现场实际上使它们成为模型的验证规则。