One of the (Symfony based) PHP projects I’m working on contains a form which allows the user to generate video clips from CCTV footage. To do this the user can enter a start and stop DateTime
. For this to work the submitted input data is then checked: both start and stop must be dates, and the stop date must be set to a point in time after the start date.
Symfony’s DateTime
Constraint can make sure both entries are DateTime
instances. To check whether that the end date is after the begin date, one can use the Callback
Constraint. Injected into that callback is a ExecutionContextInterface
by which you can access the form, and thus other form params.
Here’s an example with the inputs start
and stop
:
use Symfony\Component\Validator\Constraints;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
// …
$builder
->add('start', 'datetime',
'constraints' => [
new Constraints\NotBlank(),
new Constraints\DateTime(),
],
])
->add('stop', 'datetime', [
'constraints' => [
new Constraints\NotBlank(),
new Constraints\DateTime(),
new Constraints\Callback(function($object, ExecutionContextInterface $context) {
$start = $context->getRoot()->getData()['start'];
$stop = $object;
if (is_a($start, \DateTime::class) && is_a($stop, \DateTime::class)) {
if ($stop->format('U') - $start->format('U') < 0) {
$context
->buildViolation('Stop must be after start')
->addViolation();
}
}
}),
],
]);
If you want to have a minimum duration between both start
and stop
, you can change the number 0
in the snippet above to any number of seconds.
Thank me with a coffee.
I don\'t do this for profit but a small one-time donation would surely put a smile on my face. Thanks!
To stay in the loop you can follow @bramus or follow @bramusblog on Twitter.