1

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;

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Don't know if you can do it in anotation, but you can do it with a class validator, where you can access all the data of your entity and compare them

http://symfony.com/doc/current/validation/custom_constraint.html#class-constraint-validator

1 Comment

Yup, or you can make a custom validation constraint that grabs the other value

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.