Symfony2: how to make FOSUserBundle username unique

Hi, I have my own User class that inherits FOS\UserBundle\Entity\User . In addition, I wrote my own registration procedure. Now I have a problem that the form does not guarantee that the username is unique. I always get SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'myusername' for key 'UNIQ_2DA1797792FC23A8'

I tried adding the @UniqueEntity("email") annotation, as indicated in the documentation [1], but without any effect.

Does anyone know what might be wrong?

[1] http://symfony.com/doc/current/reference/constraints/UniqueEntity.html

+4
source share
3 answers

The restriction already exists in the FOS package. You probably need to set the validation_groups option in your form to array('Registration') .

+10
source

If you use the fos_user package, you can simply use the UniqueEntity restriction: http://symfony.com/doc/2.0/reference/constraints/UniqueEntity.html .

To implement it, just make sure your user class contains the correct usage statements and then annotations, for example (assuming you use annotations):

 <?php // ... use Symfony\Component\Validator\Constraints as Assert; use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity; /** * @ORM\Entity * @ORM\Table(name="fos_user") * @UniqueEntity("email") * @UniqueEntity("username") */ class User extends BaseUser { /* ... */ } 
+12
source

You can try this on validation.yml by checking your custom entity:

 constraints: - FOS\UserBundle\Validator\Unique: property: usernameCanonical message: 'This username already exists. Please choose another one.' 
0
source

Source: https://habr.com/ru/post/1389476/


All Articles