Yii - dynamically change rules from controller

后端 未结 5 838
太阳男子
太阳男子 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:56

    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;
    }
    

提交回复
热议问题