首页 > 解决方案 > CakePHP 3 自定义验证:如何在编辑期间将新值与旧值进行比较?

问题描述

我有一个案例,我想让用户只在编辑期间增加价值。为此,我必须将请求中传递的新值与存储在数据库中的实体的旧值进行比较。

自定义验证函数接收两个参数:$check一个要验证的值和$context一个包含来自提交表单的其他值的数组。

在 CakePHP 3 中以我需要的方式验证版本的最佳方法是什么?甚至可以使用验证规则吗?

标签: phpvalidationcakephp-3.0

解决方案


您可以使用应用程序规则

您必须在 Table 对象中创建一个新规则

假设您要检查的字段是priority

因此,在您的规则中,您检查priority(刚刚更改的)的值与存储在$entity->getOriginal('priority')

public function buildRules(RulesChecker $rules)
{

    // This rule is applied for update operations only
    $rules->addUpdate(function ($entity, $options) {
        if($entity->priority >= $entity->getOriginal('priority'))
            return true;
        else
            return false;
    }, 
    'CheckPriority', // The name of the rule
    [
        'errorField' => 'priority', // the field you want 
                                    // to append the error message
        'message' => 'You have to set a higher Priority' // the error message
    ]);

    return $rules;
}

推荐阅读