Symfony2: How to make username of FOSUserBundle us

2019-03-21 15:36发布

Hi I have my own User Class, wich inherits FOS\UserBundle\Entity\User. Additionally I wrote my own registration routine. Now I have the problem that the form does not make sure 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 stated in the documentation[1], but without any effect.

Someone knows what might be wrong?

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

3条回答
贼婆χ
2楼-- · 2019-03-21 15:53

If you're using the fos_user bundle, you can simply use the UniqueEntity constraint: http://symfony.com/doc/2.0/reference/constraints/UniqueEntity.html.

To implement it, just make sure your User class constains the proper use statements, and then the annotations, like so (assuming you're using 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
{ /* ... */ }
查看更多
女痞
3楼-- · 2019-03-21 15:59

You can try this on the validation.yml with your user entity validation:

constraints:    
    - FOS\UserBundle\Validator\Unique:
        property: usernameCanonical
        message:  'This username already exists. Please choose another one.'
查看更多
女痞
4楼-- · 2019-03-21 16:07

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

查看更多
登录 后发表回答