Class constraints in Symfony2

Sometimes you need to put a constraint on a whole class, rather than a single value. Duplicate usernames are a good example of this – you don’t want to be able to set a username to one that is already in use – but if it is in use with the user you are currently working on, you don’t want to flag it up as an error!

Lets use that as an example. You have a Username constraint and a UsernameValidator object to do the actual validation. We need to supply the validator an object, so we need to put the following method inside the Username object.

public function getTargets()
    return self::CLASS_CONSTRAINT;

This will turn the first parameter in our isValid function in the UsernameValidator class to an object.

public function isValid($user, Constraint $constraint)

Finally, you can call the constraint from your YAML validation file.

        - nocs:UniqueUsername: ~

Normally, under user you would have getters and properties – but here we’re adding a new section named “constraints” which lists all the class constraints.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.