Yii Framework Forum: CActiveRecordBehavior should add dynamically rules - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

CActiveRecordBehavior should add dynamically rules How to add a model rule via behavior Rate Topic: -----

#1 User is offline   mintao 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 62
  • Joined: 02-December 09
  • Location:Munich, Germany

Posted 01 May 2011 - 12:48 PM

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
0

#2 User is offline   phtamas 

  • Advanced Member
  • PipPipPip
  • Yii
  • Group: Members
  • Posts: 445
  • Joined: 26-February 11
  • Location:Mezőtúr, Hungary

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.
0

#3 User is offline   chikazaki 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 3
  • Joined: 20-May 09

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


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.
0

#4 User is offline   Clem 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 30
  • Joined: 15-November 10

Posted 31 August 2012 - 01:18 PM

You can process like that:

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);
}

0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users