簡體   English   中英

Yii2:從 3rd 方模塊添加/刪除模型中的驗證規則

[英]Yii2: Add/remove validation rules in Model from 3rd party module

在主要的 Yii2 應用程序中,我們如何將驗證規則添加到第三方模塊附帶的模塊(或ActiveRecord )中?

我們可以修改現有規則嗎? 假設我們有以下規則:

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

我們將如何添加或刪除“范圍”數組中的任何貨幣?

請記住,我們不能簡單地擴展類並覆蓋rules()因為這不會更改模塊正在使用的父類。 如果以上是不可能的,請闡明設計模塊以支持其模型/活動記錄中的驗證規則定制的正確方法。

編輯 2021:在重新審視這個問題時......不要這樣做。 這似乎是正確的方法,但事實並非如此。 當您收到神秘的驗證錯誤而您不知道它們來自哪里時,您最終會陷入困境。

我為我的項目做了同樣的事情。 實際上我在模型上定義了一個 getter(根據用戶的一些信息從數據庫中讀取一些規則)並將默認規則與我的新規則合並,聽起來像這樣:

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

您可以在 rules() 方法中創建規則作為鍵 -> 數組

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

在子類中按鍵取消設置規則

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM