Yii - dynamically change rules from controller

后端 未结 5 942
别那么骄傲
别那么骄傲 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 12:05

    One approach is to use a custom validation rule. For example, the rule:

    array('colour', 'requiredOnHasColour'),
    

    And then the validator method in the same model class:

    public function requiredOnHasColour($attribute, $params) {
        if ($this->hasColour && $this->$attribute == null)
            $this->addError($attribute, 'Colour is required.');
    }
    

    More info: Create your own validation rule

提交回复
热议问题