Einius
Einius

Reputation: 1382

Symfony2 validation getters error for a specific field

I'm using Symfony2 validation getters to validate if endDate is later than startDate. It works fine except that I want the error to appear for endDate field not above the whole form. All other validation errors appears above the field it validates. Is there any way to do that?

validation part in my Entity:

/**
 * @Assert\True(message = "Invalid date")
 */
public function isDatesValid()
{
    return ($this->startDate < $this->endDate);
}

Upvotes: 1

Views: 173

Answers (1)

Chris
Chris

Reputation: 470

I don't think there is a way to achieve that with a getter validation.

Instead you could use a custom constraint: http://symfony.com/doc/current/cookbook/validation/custom_constraint.html

You'll need to overide the getTargets() method in order to access all properties:

class DateRangeConstraint extends Constraint {

    public $message = 'Your message';

    public function getTargets() {
        return Constraint::CLASS_CONSTRAINT;
    }
}

class DateRangeConstraintValidator extends ConstraintValidator {

     public function validate($obj, Constraint $constraint) {
         if ($obj->startDate() < $obj->endDate()) {
             $this->context->addViolationAt(
                'startDate',
                 $constraint->message,
                array(),
                null
         );
    }
}

}

Assign this constraint to one or both properties.

Upvotes: 2

Related Questions