【问题标题】:CakePHP Validate a specific rule only when a couple required fields aren't emptyCakePHP 仅在几个必填字段不为空时验证特定规则
【发布时间】:2015-09-17 21:58:02
【问题描述】:

我编写了一个自定义规则方法,用于在添加新记录之前验证数据库中是否存在记录。我将方法放入行为中,以便与其他模型共享它,但我遇到了先有鸡还是先有蛋的情况。

为了知道一个类别是否已经有一个特定的组名,我需要知道类别 id 和组名。所以我通过使用我的自定义规则(category_id 和 name)传递这些键。但是,这是行不通的,因为如果我没有错误地选择 category_id,那么查询将只发生在名称上,所以我用几行修补了它,但如果是这种情况则需要返回 true 并继续category_id 验证无效。

有没有更好的方法来实现这种验证?这不是我想的那么糟糕吗?或者只是不要打扰并在我的控制器中删除 hasAny() 如果它通过了我对 validates() 的调用。

MODEL:
public $validate = [
    'category_id' => [
        'rule'    => 'notEmpty',
        'message' => 'Category is required.'
    ],
    'name'      => [
        'notEmpty'     => [
            'rule'    => 'notEmpty',
            'message' => 'Team is required.'
        ],
        'recordExists' => [
            'rule'    => [ 'recordExists', [ 'category_id', 'name' ] ],
            'message' => 'Group already exists.'
        ]
    ]
];

// BEHAVIOR:
public function recordExists( Model $Model, $conditions, $requireKeys )
{
    // Overrite conditions to
    $conditions = $Model->data[ $Model->name ];

    // Trim all array elements and filter out any empty indexes
    $conditions = array_map( 'trim', $conditions );
    $conditions = array_filter( $conditions );

    // Get the remaining non-empty keys
    $conditionKeys = array_keys( $conditions );

    // Only query for record if all required keys are in conditions
    if (empty( array_diff( $requireKeys, $conditionKeys ) )) {
        return !$Model->hasAny( $conditions );
    }

    // NOTE: seems wrong to return true based on the assumption the category_id validation has probably failed
    return true; 
}

【问题讨论】:

    标签: validation cakephp cakephp-2.4


    【解决方案1】:

    使用模型的beforeValidate() 回调来检查字段是否存在以及它们是否为空。如果它们是空的,只需 unset() 模型验证属性中的 recordExists 验证规则。将它们复制到临时变量或属性中,以备您在当前操作后重新设置它们。

    如果通过具有不同名称的关联使用模型,则使用$Model->aliasname 将中断。

    $conditions = $Model->data[ $Model->name ];
    

    【讨论】:

      猜你喜欢
      • 2016-09-07
      • 2018-07-03
      • 1970-01-01
      • 2018-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-15
      相关资源
      最近更新 更多