在CakePHP3中,如何创建自定义模型规则,以验证时间是否在同一个表中的另一个时间之后?

时间:2015-08-05 13:22:11

标签: validation cakephp orm model cakephp-3.0

列(两种数据类型时间):

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?
}

我似乎无法在网上找到任何这样做的例子。

1 个答案:

答案 0 :(得分:0)

我不太确定并且没有经过测试,但也许这会给你一些提示:

$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);
}

我也不确定最后一个功能是私有还是公共...