Alex Rivera | Logout

How to validate a property dependent on another property in Symfony 2

Asked 2012-09-04T09:39:12.800
35

Is it possible to validate a property of a model class dependent on another property of the same class?

For example, I have this class:

class Conference
{
    /** $startDate datetime */
    protected $startDate;

    /** $endDate datetime */
    protected $endDate;
}

and I want that Symfony 2.0 validates, that $startDate has to be after $endDate.

Is this possible by annotations or do I have to do this manually?

Edit
Report

1 Answer

22

Yes with the callback validator: http://symfony.com/doc/current/reference/constraints/Callback.html

On symfony 2.0:

use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\ExecutionContext;

/**
 * @Assert\Callback(methods={"isDateValid"})
 */
class Conference
{

    // Properties, getter, setter ...

    public function isDateValid(ExecutionContext $context)
    {
        if ($this->startDate->getTimestamp() > $this->endDate->getTimestamp()) {
                $propertyPath = $context->getPropertyPath() . '.startDate';
                $context->setPropertyPath($propertyPath);
                $context->addViolation('The starting date must be anterior than the ending date !', array(), null);
        }
    }
}

On symfony master version:

    public function isDateValid(ExecutionContext $context)
    {
        if ($this->startDate->getTimestamp() > $this->endDate->getTimestamp()) {
            $context->addViolationAtSubPath('startDate', 'The starting date must be anterior than the ending date !', array(), null);
        }
    }

Here I choose to show the error message on the startDate field.

answered 2012-09-04T09:45:36.127

Your Answer