Override A Rule Defined In Model File

[size="3"]Is it possible to Override a rule defined in model file (public function rules()) by another method in same model?[/size]

[size="3"]what i need is, to override a default validator on a attribute which i have already defined under public function rules(). [/size]

[b]

[/b]


public function rules() {

 array('coupon_count', 'default', 'value'=>-1, 'setOnEmpty'=>true),

}

[b]

[/b]

something like below.

[b]

[/b]

if (A > b ) {

[b]

[/b]

//overriding rule defined in public function rules(){}

[b]

[/b]

}

[b]

[/b]

else {

[b]

[/b]

//using what is defined under public function rules(){}

[b]

[/b]

}

[b]

[/b]

is this possible ?

bump

i tried with below way but cdnt make it work yet. any idea ?




$validators = $this->getValidatorList();

         $params = array('value'=>-1, 'setOnEmpty'=>true); // etc

         $validator = CValidator::createValidator('default', $this, 'coupon_type', $params);

         $validators->add($validator);

Hi my friend

The one way is having the decision on method rule

public function rules() {

if (a>0) return array(‘coupon_count’, ‘default’, ‘value’=>-1, ‘setOnEmpty’=>true);

else

return array(‘coupon_count’, ‘default’, ‘value’=>-1, ‘setOnEmpty’=>true);

}

the another way is make your method to validate something and use save or something like that with false

for example

if ($yourmodel->yourMethodvalidate($yourparameters)) {

$yourmodel->save(false);

}

Thanks for the reply. Please look at my last comment. i wanted to add a default value as mentioned. is it possible ? btw is it a good practice to use the first method you said ?

It’s hard to say from the code you’ve provided, but if you’re just trying to set a default in certain circumstances, you could replace your default validator with a custom validation function like so:




    public function rules()

    {

        ...

        array('coupon_count', 'setCouponCountDefault'),

        ...

    }


    public function setCouponCountDefault($attribute, $params)

    {

        if ($shouldSetDefault)

        {

            if ($this->coupon_count === null || $this->coupon_count === '')

                $this->coupon_count = -1;

        }

    }



Obviously, replace the above with relevant tests.

If you know before instantiating the model whether the default should apply or not, you can use scenarios instead.