【问题标题】:Yii2: Add/remove validation rules in Model from 3rd party moduleYii2:从第 3 方模块中添加/删除模型中的验证规则
【发布时间】:2017-01-11 04:41:53
【问题描述】:

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

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

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

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

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

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

【问题讨论】:

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


    【解决方案1】:

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

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

    在子类中按键取消规则

    $parent = parent::rules();
    unset($parent['test']);
    return $parent;
    

    【讨论】:

      【解决方案2】:

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

      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
       */
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-09-05
        • 2015-07-05
        • 2021-10-17
        • 2019-05-22
        • 2018-02-22
        • 1970-01-01
        • 2016-11-16
        相关资源
        最近更新 更多