Yii - dynamically change rules from controller

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

    You can use scenario. In the model:

    class Model extends CActiveRecord {
        // ....
        public function rules() {
            return array(
                array('colour', 'required', 'on' => 'hasColour')
            );
        }
        // ....
    }
    

    And in the controller:

    public function actionOrder() {
        // ....
        $model = new Product();
        if ($product->HasColour) {
            $model->setScenario('hasColour');
        }
    }
    

    So, required colour will be validated when the model's scenario is hasColour

提交回复
热议问题