0

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

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

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

我们如何在“范围”数组中添加或删除任何货币?

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

编辑 2021:在重新审视这个问题后......只是不要这样做。这似乎是正确的方法,但事实并非如此。当您遇到您不知道它们来自哪里的神秘验证错误时,您最终会大发雷霆。

4

2 回答 2

0

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

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
 */
于 2016-09-03T05:03:20.290 回答
0

您可以在 rules() 方法中将规则创建为键 -> 数组

$rules = [
['id', 'integer'],
'test' => ['name', 'string'], 
];

在子类中按键未设置规则

$parent = parent::rules();
unset($parent['test']);
return $parent;
于 2021-11-09T12:32:26.997 回答