Yii - dynamically change rules from controller

后端 未结 5 935
别那么骄傲
别那么骄傲 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:48

    In your ActiveRecord you can add in any place dynamic validator. For example i overwrite parent method setAttributes and add $this->validatorList->add() depends on selected value in $this->type attribute. Official docs: https://www.yiiframework.com/doc/api/1.1/CValidator

    public function setAttributes($values, $safeOnly = true)
    {
        $result = parent::setAttributes($values, $safeOnly);
    
        if (self::TYPE_PHONE == $this->type) {
            $this->validatorList->add(CValidator::createValidator('required', $this, ['phone', 'phonePrefix']));
        } elseif (self::TYPE_EMAIL == $this->type) {
            $this->validatorList->add(CValidator::createValidator('required', $this, ['email']));
        }
    
        return $result;
    }
    

提交回复
热议问题