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?
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
. After browsing this source code for a while I came up with the following piece of code, mostly ripped from CModel
itself:
$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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.