【问题标题】:Validating length depending on a setting in CakePHP根据 CakePHP 中的设置验证长度
【发布时间】:2014-01-26 16:02:34
【问题描述】:

请注意,我使用的是 CakePHP 1.3。

我想根据管理员在数据库中定义的限制来验证模型的几个字段的长度。

我有一个名为 Setting 的模型,通过它我可以获取 maxLength 值。我的想法是使用 beforeValidate 方法来获取它们,然后相应地设置 $validate 参数:

<?php
class Mod extends AppModel
{   
    var $belongsTo = array('IBelong');
    var $hasMany = array('IHaz');

    function beforeValidate() {
        // Fetch the maxLength settings : requestAction to the SettingsController ?
        // Somehow do $this->Setting->find... ?

        // Then set the $validate attribute
    }
}
?>

我可以使用什么方法在 beforeValidate 回调中获取 maxLength 值?

谢谢!

编辑:跟随 Dave 的 cmets,这是我目前正在做的事情(并且有效):

<?php
class Mod extends AppModel
{   
    var $belongsTo = array('IBelong');
    var $hasMany = array('IHaz');

    function beforeValidate() {
        App::import('Model', 'Setting');
        $setting = new Setting();
        // Use $setting->find... to fetch the settings
        // Set the $validate attribute to validate using the settings
    }
}
?>

但是,我仍然不确定这是否是正确的方法。

请注意,我有几个要验证的属性,并且我希望避免多次调用 $setting->find 以获得最佳性能。

【问题讨论】:

    标签: validation cakephp cakephp-1.3


    【解决方案1】:

    CakePHP book 中对数据验证进行了非常详尽的解释。

    如果您阅读Custom Validation Rules area,您会看到他们从数据库中提取数据以用于验证的示例 - 完全符合您的要求。

    (这里是Custom Validation Rules for 1.3)

    【讨论】:

    • 我确实看到了这个例子,但我想知道 a) 当我尝试保存模型时,这会调用每个字段的函数吗?我想避免进行 5 个 SQL 查询,这就是我想使用 beforeValidate 的原因。 b) 如何从这个回调中调用 Setting 模型的 find 方法?
    • 为什么不做你在代码中写的 - $this->Setting->find() 假设 Setting 与 Mod 相关联没有错。然后将您的设置设置为 $this->data['Setting'][] 或其他内容。
    • 但是如果 Setting 没有与 Mod 关联呢?我的 Setting 模型用于存储应用程序的通用设置,因此 Setting 和 Mod 之间没有真正的语义联系(使用 belongsTo 或 hasMany 没有意义)
    • @personne3000: loadModel()
    • 我确实对这一切有所了解,但由于我对 cakePHP 没有经验,所以我并不真正知道如何将所有部分组合在一起。我应该可以让它与 loadModel 一起工作,谢谢
    猜你喜欢
    • 2011-02-21
    • 1970-01-01
    • 2018-04-12
    • 1970-01-01
    • 2021-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-27
    相关资源
    最近更新 更多