CakePHP 3 自定义验证:如何在编辑期间比较新值与旧值?
CakePHP 3 custom validation: how to compare new value with old value during edit?
我有一个案例,我想让用户只在编辑期间增加价值。为此,我必须将请求中传递的新值与存储在数据库中的实体的旧值进行比较。
自定义验证函数接收两个参数:$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;
}
我有一个案例,我想让用户只在编辑期间增加价值。为此,我必须将请求中传递的新值与存储在数据库中的实体的旧值进行比较。
自定义验证函数接收两个参数:$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;
}