2012-01-05 68 views
4

嗨,我有我自己的User类,它继承FOS\UserBundle\Entity\User。另外我写了我自己的注册程序。现在我遇到了表单不能确保用户名是唯一的问题。我总是得到SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'myusername' for key 'UNIQ_2DA1797792FC23A8'Symfony2:如何使FOSUserBundle用户的用户名唯一

我试着在文档[1]中添加@UniqueEntity("email")注释,但没有任何效果。

有人知道什么可能是错的?

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

回答

10

约束存在于FOS已捆绑。您可能需要将表单上的validation_groups选项设置为array('Registration')

+0

这不会有任何影响:/还有什么想法? – stoefln 2012-01-09 13:42:51

+0

但是,这里是链接到文档:http://symfony.com/doc/2.0/book/forms.html#book-forms-validation-groups – stoefln 2012-01-11 11:48:44

+2

在github上发布了一个问题。那里有很棒的支持团队非常感谢@stof指出我没有实际验证用户对象,而只是表单数据。更多信息:https://github.com/FriendsOfSymfony/FOSUserBundle/issues/480 – stoefln 2012-01-12 11:12:58

0

您可以与您的用户实体验证的validation.yml试试这个:

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

如果您使用的fos_user包,你可以简单地使用UniqueEntity约束:http://symfony.com/doc/2.0/reference/constraints/UniqueEntity.html

要实现它,只要确保你的用户类constains正确使用语句,然后注释,像这样(假设你使用注释):

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

只想说感谢Vraxoin!在我的单元测试期间,当我尝试注册一个已存在的用户名时,我得到了一个丑陋的DB级别违规(SQLSTATE [23000]:完整性约束违规)......我搜索了很高和低,发现了许多复杂的答案他们真的看起来像他们会解决这个问题)。一时兴起,我给了这个镜头(只有4行复制和粘贴正确吗?),现在我的非唯一注册尝试现在处于正常处理状态(FOSUB现在再次将用户重定向到注册表单,而不是数据库例外)。谢谢你,谢谢你,谢谢你! – jfgrissom 2014-07-16 07:45:32

相关问题