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:
1 2 3 4 5 6 7 8 9 10 11 |
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity; // codes not relevant to this example has been removed /** * @UniqueEntity(fields="email", message="Email is already in use") * @UniqueEntity(fields="username", message="Username is already in use") */ class User { } |
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 ?