is it somehow possible to add additional rules to a model via behavior?
if my behavior is added to a model, I've to ensure a certain value format (a date in my case).
Thanks for your help
Page 1 of 1
CActiveRecordBehavior should add dynamically rules How to add a model rule via behavior
#2
Posted 01 May 2011 - 03:12 PM
Behaviors can't add rules to models directly (AFAIK), but you can implement beforeValidate() or afterValidate() method in your behavior, and use addError() if an attribute is invalid.
#3
Posted 17 August 2012 - 10:04 PM
mintao, on 01 May 2011 - 12:48 PM, said:
is it somehow possible to add additional rules to a model via behavior?
if my behavior is added to a model, I've to ensure a certain value format (a date in my case).
Thanks for your help
if my behavior is added to a model, I've to ensure a certain value format (a date in my case).
Thanks for your help
try this
in your model (or base model)
public function rules()
{
$rules = array( /* your rules */ );
//add all rules from attached behaviors
$behaviors = $this->behaviors();
foreach($behaviors as $key=>$behavior)
{
if( method_exists($this->{$key},'rules') )
$rules += $this->{$key}->rules();
}
return $rules;
}
and if you have extned models then
public function rules()
{
return array_merge(parent::rules(),array(
/* your rules for this extended model */
));
}
(caution) Properties should not be conflicted.
#4
Posted 31 August 2012 - 01:18 PM
You can process like that:
In your Behavior overwrite the attach method:
In your Behavior overwrite the attach method:
/**
* Attach the behavior to the model.
* @param model $owner
*/
public function attach($owner) {
parent::attach($owner);
$owner = $this->getOwner();
$validators = $owner->getValidatorList();
$params = array('types' => 'jpg, jpeg, gif, png'); // etc
$validator = CValidator::createValidator('file', $owner, 'MyModel[attribute]',$params );
$validators->add($validator);
}
Share this topic:
Page 1 of 1

Help











