Yii - dynamically change rules from controller

后端 未结 5 841
太阳男子
太阳男子 2021-02-09 11:08

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:55

    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

提交回复
热议问题