I have a class called Student with a StartDate and EndDate. I would like to add an \@Assert()
where it verifies that StartDate is always BEFORE EndDate. This is what I have thus but the error message is not being executed. Can this be accomplished another way.
/**
* @var \DateTime
*
* @ORM\Column(name="startDate", type="datetime", nullable=false)
* @Assert\Type("DateTime")
*/
private $startdate;
/**
* @var \DateTime
*
* @ORM\Column(name="endDate", type="datetime", nullable=false)
* @Assert\Type("DateTime")
* @Assert\Expression("this.getStartDate() < this.getEndDate()",
* message="The end date must be after the start date")
*
*
*/
private $enddate;
You could use a simple callback:
/**
* @var \DateTime
*
* @ORM\Column(name="startDate", type="datetime", nullable=false)
* @Assert\Type("DateTime")
*/
private $startdate;
/**
* @var \DateTime
*
* @ORM\Column(name="endDate", type="datetime", nullable=false)
* @Assert\Type("DateTime")
* message="The end date must be after the start date")
*
*
*/
private $enddate;
/**
* @Assert\Callback
*/
public function validateDate(ExecutionContextInterface $context, $payload)
{
if ($this->startdate > $this->enddate) {
$context->buildViolation('Start date has to be before end date')
->atPath('startdate')
->addViolation();
}
}
see https://symfony.com/doc/current/reference/constraints/Callback.html for details.