@@ -100,6 +100,27 @@ between all of the rows in your user table:
100
100
}
101
101
}
102
102
103
+ // src/Form/Type/UserType.php
104
+ namespace App\Form\Type;
105
+
106
+ use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
107
+
108
+ class UserType extends AbstractType
109
+ {
110
+ // ...
111
+
112
+ public function configureOptions(OptionsResolver $resolver): void
113
+ {
114
+ $resolver->setDefaults([
115
+ // ...
116
+ 'data_class' => User::class,
117
+ 'constraints' => [
118
+ new UniqueEntity(fields: ['email']),
119
+ ],
120
+ ]);
121
+ }
122
+ }
123
+
103
124
.. warning ::
104
125
105
126
This constraint doesn't provide any protection against `race conditions `_.
@@ -116,8 +137,9 @@ between all of the rows in your user table:
116
137
Using a PHP class
117
138
-----------------
118
139
119
- This constraint can also check **uniqueness on any PHP class ** and not only on
120
- Doctrine entities. Consider the following Doctrine entity::
140
+ This constraint can also check **uniqueness on any PHP class ** that is mapped to
141
+ a Doctrine entity, and not only on Doctrine entities. Consider the following
142
+ Doctrine entity::
121
143
122
144
// src/Entity/User.php
123
145
namespace App\Entity;
@@ -160,8 +182,6 @@ following using the `entityClass`_ option:
160
182
)]
161
183
class UserDto
162
184
{
163
- public ?int $id = null,
164
-
165
185
#[Assert\Email]
166
186
public ?string $email = null;
167
187
}
@@ -208,8 +228,6 @@ following using the `entityClass`_ option:
208
228
209
229
class UserDto
210
230
{
211
- public ?int $id = null;
212
-
213
231
public ?string $email = null;
214
232
215
233
public static function loadValidatorMetadata(ClassMetadata $metadata): void
@@ -353,7 +371,7 @@ the combination value is unique (e.g. two users could have the same email,
353
371
as long as they don't have the same name also).
354
372
355
373
If you need to require two fields to be individually unique (e.g. a unique
356
- ``email `` and a unique ``username ``), you should use two ``UniqueEntity `` entries,
374
+ ``email `` and a unique ``username ``), you must use two ``UniqueEntity `` entries,
357
375
each with a single field.
358
376
359
377
When `using a PHP class `_, the names of the unique fields may differ
@@ -721,6 +739,10 @@ a key-value mapping:
721
739
}
722
740
}
723
741
742
+ .. note ::
743
+
744
+ This option has no effect when the constraint is applied to an entity.
745
+
724
746
``message ``
725
747
~~~~~~~~~~~
726
748
0 commit comments