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