Yii2:在第三方模块的模型中添加/删除验证规则

时间:2016-09-03 03:38:15

标签: activerecord module yii2 yii2-model yii2-module

在主Yii2应用程序中,我们如何将验证规则添加到第三方模块附带的Module(或ActiveRecord)?

我们可以修改现有规则吗?假设我们有以下规则:

['currency', 'in', 'range' => ['USD', 'GBP', 'EUR']],

我们如何在'范围内添加或删除任何货币?阵列

请记住,我们不能简单地扩展类并覆盖rules(),因为这不会更改模块正在使用的父类。如果上述情况不可能,请详细说明设计模块的正确方法,以支持其模型/活动记录中的验证规则定制。

1 个答案:

答案 0 :(得分:0)

我为我的项目做了同样的事情。实际上我在一个模型上定义了一个getter(根据用户的一些信息从db读取一些规则)并将默认规则与我的新规则合并,听起来像这样:

public function getDynamicRules()
{
    $rules = [];

    if (1 > 2) { // Some rules like checking the region of your user in your case
        $rules[] = ['currency', 'min' => '25'];
    }

    return $rules;
}

public function rules()
{
    $oldRules = [
        ['currency', 'in', 'range' => ['USD', 'GBP', 'EUR']],
    ];

    return array_merge(
        $oldRules,
        $this->dynamicRules
    );
}

此外,如果您的模型完全是动态的,您可以轻松地从yii\base\DynamicModel扩展模型。它有很多方法可以帮助您实现动态模型。在规则方面,您可以使用DynamicModel::addRule方法来定义一些新规则。来自DynamicModel的文档:

/**
 * Adds a validation rule to this model.
 * You can also directly manipulate [[validators]] to add or remove validation rules.
 * This method provides a shortcut.
 * @param string|array $attributes the attribute(s) to be validated by the rule
 * @param mixed $validator the validator for the rule.This can be a built-in validator name,
 * a method name of the model class, an anonymous function, or a validator class name.
 * @param array $options the options (name-value pairs) to be applied to the validator
 * @return $this the model itself
 */
相关问题