Yii - dynamically change rules from controller

后端 未结 5 940
别那么骄傲
别那么骄傲 2021-02-09 11:15

Let\'s say I have a product which can have a colour. Depending on the product type, the colour field may or may not be required.

If colour is always required, I would ha

5条回答
  •  心在旅途
    2021-02-09 11:44

    If you want to do more complicated logic, then scenarios might not satisfy your needs. Then you can override method init and do all the logic that define validation rules over there, adding results to $validationRules array. And the in rules() method you just return that array. Something like that:

     class Person extends CActiveRecord
    {
        public function init(){
            if( TRUE){
                $this->validationRules[] = array('first_name','required');
                $this->validationRules[] = array('last_name','required');
            }
    
        }
    
        public $validationRules = array(
            array('email', 'required'),
            array('email, email1, email2, email3', 'email', 'message'=>'Email format is invalid'),
            array('email, address, email1, email2, email3', 'length', 'max'=>255),
    
        );
    
        public function rules()
        {
            return $this->validationRules;
        }
    }
    

提交回复
热议问题