CakePHP 3自定义验证:如何在编辑期间将新值与旧值进行比较?

问题描述 投票:0回答:1

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

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

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

php validation cakephp-3.0
1个回答
1
投票

你可以使用Application Rules

您必须在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;
}
© www.soinside.com 2019 - 2024. All rights reserved.