【问题标题】:In CakePHP3 how do I create a custom model rule which validates that a time is after another time in the same table?在 CakePHP3 中,我如何创建一个自定义模型规则来验证同一个表中的某个时间是在另一个时间之后?
【发布时间】:2015-08-05 13:22:10
【问题描述】:

列(数据类型均为时间):

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

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

【问题讨论】:

  • 那么你不明白的到底是什么?如何查询数据?如何从验证规则访问表?如何判断请求是否包含开始日期?

标签: validation cakephp orm model cakephp-3.0


【解决方案1】:

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

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

我也不确定最后一个函数是私有的还是公共的......

【讨论】:

  • 太好了,谢谢。标记为答案,因为这似乎比我试图实现的更容易。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-26
相关资源
最近更新 更多