我有一个案例,我想让用户只在版本期间增加价值。为此,我必须将请求中传递的新值与存储在DB中的实体的旧值进行比较。
自定义验证函数接收两个参数:$check
,它是要验证的值,数组$context
包含提交表单中的其他值。
在CakePHP 3中以我需要的方式验证版本的最佳方法是什么?甚至可以使用验证规则吗?
你可以使用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;
}