php - CakePHP 3 自定义验证:如何在编辑期间将新值与旧值进行比较?
问题描述
我有一个案例,我想让用户只在编辑期间增加价值。为此,我必须将请求中传递的新值与存储在数据库中的实体的旧值进行比较。
自定义验证函数接收两个参数:$check
一个要验证的值和$context
一个包含来自提交表单的其他值的数组。
在 CakePHP 3 中以我需要的方式验证版本的最佳方法是什么?甚至可以使用验证规则吗?
解决方案
您可以使用应用程序规则
您必须在 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;
}
推荐阅读
- python - 在 Python 中进行人脸识别的 Face Anti-Spoofing 方法
- json - 使用 Alamofire 在多形式 Swift 的参数中附加嵌套对象
- java - 如何将方法内部的字符串数组传递给另一个方法?
- android - 从 GridViewFragment 到 ViewPager2Fragment 的 Android ShareElement 奇怪
- node.js - 安装后 nyc 无法识别为命令
- verilog - 在verilog中将inout数组拆分为多个inout信号
- qml - 使用文本和矩形在 qml 中设计 3 个中间点 (...)
- c# - 使用 Pinvoke 调用 AppContainer 安全功能的 UpdateProcThreadAttribute 时失败
- javascript - 木偶抓取;向搜索栏添加文本返回错误
- java - 如何避免杰克逊将字段标记为 FetchType.LAZY?