2013-02-18 85 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)))); 
} 

現在,這可以讓我去,看起來像驗證規則的模型數組元素的列表並在現場實際上使它們成爲模型的驗證規則。