Symfony2: How to make username of FOSUserBundle user unique

99封情书 提交于 2019-12-03 08:52:40

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

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
{ /* ... */ }

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.'
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!