Yii - dynamically change rules from controller

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

    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

提交回复
热议问题