Yii - 从控制器动态更改规则 [英] Yii - dynamically change rules from controller

查看:18
本文介绍了Yii - 从控制器动态更改规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个可以有颜色的产品.根据产品类型,颜色字段可能需要也可能不需要.

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 have the following in the product model

public function rules()
{
    return array(
        array('colour', 'required')
    );
}

但是,我希望它是动态的,具体取决于产品类型.

However, I want this to be dynamic depending on the product type.

这应该在控制器中完成吗?我想在控制器中有类似以下的内容:

Should this be done in the controller? I would imagine having something like the following in the controller:

public function actionOrder() {
    // ....
    if ($product->HasColour) {
        // set the colour validation to be required
    } else {
        // set the colour validation to be not required
    }
}

解决这个问题的最佳方法是什么?

What is the best way to approach this?

谢谢

推荐答案

您可以使用方案.在模型中:

You can use scenario. In the model:

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

在控制器中:

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

因此,当模型的场景为 hasColour

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

这篇关于Yii - 从控制器动态更改规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆