在 CakePHP3 中,我如何创建一个自定义模型规则来验证一个时间在同一 table 中的另一个时间之后?
In CakePHP3 how do I create a custom model rule which validates that a time is after another time in the same table?
列(均为时间数据类型):
Start
End
结束不能早于开始。
$validator
->requirePresence('end', 'create')
->notEmpty('end')
->add('end', [
'time' => [
'rule' => 'time',
'message' => 'end can only accept times.'
],
'dependency' => [
'rule' => [$this, 'endBeforeStart'],
'message' => 'end can not be before start.'
],
]);
如果是只包含end的PUT请求,模型将需要查询现有记录以与start进行比较。如果它是包含两者的 PUT,则需要针对预期的新参数进行验证。
cakePHP3 是如何做到这一点的?
private function endBeforeStart($fieldValueToBeValidated, $dataRelatedToTheValidationProcess)
{
//What goes here?
}
我似乎无法在网上找到任何执行此操作的示例。
我不太确定也没有测试过,但也许这会给你一些提示:
$validator
->add('end', [
'endBeforeStart' => [
'rule' => function ($value, $context) {
// If it's a POST (new entry):
if ( $context['newRecord'] == '1' ) {
// Do your comparison here
// Input values are e.g. in $context['data']['starttime']
// If end is before start:
return false;
}
// If it's a PUT (update):
else {
// If starttime is not in $context['data']['starttime']
// check for the old value in $getOldEntry
$getOldEntry = $this->getOldEntry( $context['data']['id'] );
// And do your comparison here...
// If end is before start:
return false;
}
return true;
},
'message' => 'end can not be before start.' ],
])
public function getOldEntry($id = null) {
return $this->get($id);
}
我也不确定最后一个函数是私有的还是 public...
列(均为时间数据类型):
Start
End
结束不能早于开始。
$validator
->requirePresence('end', 'create')
->notEmpty('end')
->add('end', [
'time' => [
'rule' => 'time',
'message' => 'end can only accept times.'
],
'dependency' => [
'rule' => [$this, 'endBeforeStart'],
'message' => 'end can not be before start.'
],
]);
如果是只包含end的PUT请求,模型将需要查询现有记录以与start进行比较。如果它是包含两者的 PUT,则需要针对预期的新参数进行验证。
cakePHP3 是如何做到这一点的?
private function endBeforeStart($fieldValueToBeValidated, $dataRelatedToTheValidationProcess)
{
//What goes here?
}
我似乎无法在网上找到任何执行此操作的示例。
我不太确定也没有测试过,但也许这会给你一些提示:
$validator
->add('end', [
'endBeforeStart' => [
'rule' => function ($value, $context) {
// If it's a POST (new entry):
if ( $context['newRecord'] == '1' ) {
// Do your comparison here
// Input values are e.g. in $context['data']['starttime']
// If end is before start:
return false;
}
// If it's a PUT (update):
else {
// If starttime is not in $context['data']['starttime']
// check for the old value in $getOldEntry
$getOldEntry = $this->getOldEntry( $context['data']['id'] );
// And do your comparison here...
// If end is before start:
return false;
}
return true;
},
'message' => 'end can not be before start.' ],
])
public function getOldEntry($id = null) {
return $this->get($id);
}
我也不确定最后一个函数是私有的还是 public...