validation - In CakePHP3 how do I create a custom model rule which validates that a time is after another time in the same table? -
columns (both datatype time):
start end
end cannot before start.
$validator ->requirepresence('end', 'create') ->notempty('end') ->add('end', [ 'time' => [ 'rule' => 'time', 'message' => 'end can accept times.' ], 'dependency' => [ 'rule' => [$this, 'endbeforestart'], 'message' => 'end can not before start.' ], ]);
if put request contains end, model need query existing record compare against start. if put contains both need validate against intended new parameter.
how cakephp3 this?
private function endbeforestart($fieldvaluetobevalidated, $datarelatedtothevalidationprocess) { //what goes here? }
i can't seem find examples of doing online.
i'm not quite sure , haven't tested it, maybe gives hints:
$validator ->add('end', [ 'endbeforestart' => [ 'rule' => function ($value, $context) { // if it's post (new entry): if ( $context['newrecord'] == '1' ) { // comparison here // input values e.g. in $context['data']['starttime'] // if end before start: return false; } // if it's put (update): else { // if starttime not in $context['data']['starttime'] // check old value in $getoldentry $getoldentry = $this->getoldentry( $context['data']['id'] ); // , comparison here... // if end before start: return false; } return true; }, 'message' => 'end can not before start.' ], ]) public function getoldentry($id = null) { return $this->get($id); }
i'm not sure if last function has private or public...
Comments
Post a Comment