Categories
PHP

Symfony2 Forms and Doctrine Entity: Unique field values validation

If you’re using Symfony2 forms paired with Doctrine entities, you might sometimes need to validate fields so that the values in that field is always unique. Say – “username” field or “email” field. Two users must not have the same username or email.

There is a form validation constraint – “Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity” which integrates nicely with your entity and allows unique values validation when the form is submitted. Let’s look at some code samples to see how it works:

Here, the email and username fields will be checked for duplicate values and the defined message will be displayed if duplicate values are found.

2 replies on “Symfony2 Forms and Doctrine Entity: Unique field values validation”

Hey,

 

thanx. Works great.

If you want to specify multiple fields try this:

@UniqueEntity(fields={“name”, “deleted”}, message=”entity with this name already exists”)

@UniqueEntity(fields={“name”, “name1”}, message=”entity with this name already exists”)

how to ensure uniqueness if “name” is from  another entity ?

Comments are closed.