使用Symfony2/Symfony3中的FOSUserBundle删除/用电子邮件替换用户名字段


Remove / Replace the username field with email using FOSUserBundle in Symfony2 / Symfony3

我只想用电子邮件作为登录模式,我不想用用户名。symfony2/symfony3和FOSUserbundle有可能吗?

我在这里阅读http://groups.google.com/group/symfony2/browse_thread/thread/92ac92eb18b423fe

但后来我遇到了两个违反约束的问题。

问题是,如果用户将电子邮件地址留空,我会得到两个约束违规:

  • 请输入用户名
  • 请输入电子邮件

有没有一种方法可以禁用给定字段的验证,或者有更好的方法从表单中完全删除一个字段?

需要做什么的完整概述

以下是需要做的工作的完整概述。我在这篇文章的末尾列出了不同的来源。

1.覆盖Acme'UserBundle'Entity'User中的设置器

public function setEmail($email)
{
    $email = is_null($email) ? '' : $email;
    parent::setEmail($email);
    $this->setUsername($email);
    return $this;
}

2.从表单类型中删除用户名字段

(在RegistrationFormTypeProfileFormType中)

public function buildForm(FormBuilder $builder, array $options)
{
    parent::buildForm($builder, $options);
    $builder->remove('username');  // we use email as the username
    //..
}

3.验证约束

如@nurikabe所示,我们必须摆脱FOSUserBundle提供的验证约束,创建自己的验证约束。这意味着我们必须重新创建之前在FOSUserBundle中创建的所有约束,并删除与username字段有关的约束。我们将创建的新验证组是AcmeRegistrationAcmeProfile。因此,我们完全凌驾于FOSUserBundle提供的那些之上。

3.a.更新Acme'UserBundle'Resources'config'config.yml中的配置文件

fos_user:
    db_driver: orm
    firewall_name: main
    user_class: Acme'UserBundle'Entity'User
    registration:
        form:
            type: acme_user_registration
            validation_groups: [AcmeRegistration]
    profile:
        form:
            type: acme_user_profile
            validation_groups: [AcmeProfile]

3.b.创建验证文件Acme'UserBundle'Resources'config'validation.yml

这是很长的一段:

Acme'UserBundle'Entity'User:
    properties:
    # Your custom fields in your user entity, here is an example with FirstName
        firstName:
            - NotBlank:
                message: acme_user.first_name.blank
                groups: [ "AcmeProfile" ]
            - Length:
                min: 2
                minMessage: acme_user.first_name.short
                max: 255
                maxMessage: acme_user.first_name.long
                groups: [ "AcmeProfile" ]

# Note: We still want to validate the email
# See FOSUserBundle/Resources/config/validation/orm.xml to understand
# the UniqueEntity constraint that was originally applied to both
# username and email fields
#
# As you can see, we are only applying the UniqueEntity constraint to 
# the email field and not the username field.
FOS'UserBundle'Model'User:
    constraints:
        - Symfony'Bridge'Doctrine'Validator'Constraints'UniqueEntity: 
             fields: email
             errorPath: email 
             message: fos_user.email.already_used
             groups: [ "AcmeRegistration", "AcmeProfile" ]
    properties:
        email:
            - NotBlank:
                message: fos_user.email.blank
                groups: [ "AcmeRegistration", "AcmeProfile" ]
            - Length:
                min: 2
                minMessage: fos_user.email.short
                max: 255
                maxMessage: fos_user.email.long
                groups: [ "AcmeRegistration", "ResetPassword" ]
            - Email:
                message: fos_user.email.invalid
                groups: [ "AcmeRegistration", "AcmeProfile" ]
        plainPassword:
            - NotBlank:
                message: fos_user.password.blank
                groups: [ "AcmeRegistration", "ResetPassword", "ChangePassword" ]
            - Length:
                min: 2
                max: 4096
                minMessage: fos_user.password.short
                groups: [ "AcmeRegistration", "AcmeProfile", "ResetPassword", "ChangePassword"]
FOS'UserBundle'Model'Group:
    properties:
        name:
            - NotBlank:
                message: fos_user.group.blank
                groups: [ "AcmeRegistration" ]
            - Length:
                min: 2
                minMessage: fos_user.group.short
                max: 255
                maxMessage: fos_user.group.long
                groups: [ "AcmeRegistration" ]
FOS'UserBundle'Propel'User:
    properties:
        email:
            - NotBlank:
                message: fos_user.email.blank
                groups: [ "AcmeRegistration", "AcmeProfile" ]
            - Length:
                min: 2
                minMessage: fos_user.email.short
                max: 255
                maxMessage: fos_user.email.long
                groups: [ "AcmeRegistration", "ResetPassword" ]
            - Email:
                message: fos_user.email.invalid
                groups: [ "AcmeRegistration", "AcmeProfile" ]
        plainPassword:
            - NotBlank:
                message: fos_user.password.blank
                groups: [ "AcmeRegistration", "ResetPassword", "ChangePassword" ]
            - Length:
                min: 2
                max: 4096
                minMessage: fos_user.password.short
                groups: [ "AcmeRegistration", "AcmeProfile", "ResetPassword", "ChangePassword"]

FOS'UserBundle'Propel'Group:
    properties:
        name:
            - NotBlank:
                message: fos_user.group.blank
                groups: [ "AcmeRegistration" ]
            - Length:
                min: 2
                minMessage: fos_user.group.short
                max: 255
                maxMessage: fos_user.group.long
                groups: [ "AcmeRegistration" ]

4.完

就是这样!你应该准备好了!


用于此帖子的文档:

  • 从FOSUserBundle中删除用户名的最佳方式
  • [验证]未正确覆盖
  • 唯一实体
  • 正在验证fosuserbundle注册表
  • 如何在Symfony中使用验证组
  • Symfony2使用表单中的验证组

我可以通过覆盖此处详细说明的注册和配置文件表单类型并删除用户名字段来做到这一点

$builder->remove('username');

除了覆盖我的具体用户类中的setEmail方法:

 public function setEmail($email) 
 {
    $email = is_null($email) ? '' : $email;
    parent::setEmail($email);
    $this->setUsername($email);
  }

正如Michael所指出的,这可以通过自定义验证组来解决。例如:

fos_user:
    db_driver: orm
    firewall_name: main
    user_class: App'UserBundle'Entity'User
    registration:
        form:
            type: app_user_registration
            validation_groups: [AppRegistration]

然后在您的实体(如user_class: App'UserBundle'Entity'User所定义)中,您可以使用AppRegistration组:

class User extends BaseUser {
    /**
     * Override $email so that we can apply custom validation.
     * 
     * @Assert'NotBlank(groups={"AppRegistration"})
     * @Assert'MaxLength(limit="255", message="Please abbreviate.", groups={"AppRegistration"})
     * @Assert'Email(groups={"AppRegistration"})
     */
    protected $email;
    ...

这就是我在Symfony2帖子上发布回复后所做的。

请参阅http://symfony.com/doc/2.0/book/validation.html#validation-组以获取完整的详细信息。

从Sf 2.3开始,快速解决方法是将用户名设置为类User的_construct中扩展BaseUser的任何字符串。

public function __construct()
    {
        parent::__construct();
        $this->username = 'username';
    }

这样,验证器就不会触发任何违规行为。但不要忘记将电子邮件设置为Patt发布的用户名。

public function setEmail($email)
{
    $email = is_null($email) ? '' : $email;
    parent::setEmail($email);
    $this->setUsername($email);
}

您可能需要检查其他文件中对User:username的引用,并相应地进行更改。

您尝试过自定义验证吗?

要做到这一点,您需要从UserBundle继承自己的bundle,然后复制/调整Resources/config/validation.xml。此外,您还需要将config.yml中的validation_groups设置为自定义验证。

我更喜欢替换RegistrationFormHandler#进程,而不是替换Validation,更确切地说,添加新方法processExtended(例如),它是原始方法的副本,并在RegistrationController中使用ut。(覆盖:https://github.com/FriendsOfSymfony/FOSUserBundle/blob/master/Resources/doc/index.md#next-步骤)

在我绑定注册表之前,我将用户名设置为例如"空":

class RegistrationFormHandler extends BaseHandler
{
    public function processExtended($confirmation = false)
    {
        $user = $this->userManager->createUser();
        $user->setUsername('empty'); //That's it!!
        $this->form->setData($user);
        if ('POST' == $this->request->getMethod()) {

            $this->form->bindRequest($this->request);
            if ($this->form->isValid()) {
                $user->setUsername($user->getEmail()); //set email as username!!!!!
                $this->onSuccess($user, $confirmation);
                /* some my own logic*/
                $this->userManager->updateUser($user);
                return true;
            }
        }
        return false;
    }
    // replace other functions if you want
}

为什么?我更喜欢使用FOSUserBundle验证规则。因为如果我在注册表的config.yml中替换Validation Group,我需要在我自己的用户实体中重复User的验证规则。

如果它们都不起作用,一个快速而肮脏的解决方案将是

public function setEmail($email)
{
    $email = is_null($email) ? '' : $email;
    parent::setEmail($email);
    $this->setUsername(uniqid()); // We do not care about the username
    return $this;
}

您可以将用户名设为null,然后将其从表单类型中删除:

首先,在AppBundle''Entity''User中,在User类上方添加注释

use Doctrine'ORM'Mapping'AttributeOverrides;
use Doctrine'ORM'Mapping'AttributeOverride;
/**
 * User
 *
 * @ORM'Table(name="fos_user")
 *  @AttributeOverrides({
 *     @AttributeOverride(name="username",
 *         column=@ORM'Column(
 *             name="username",
 *             type="string",
 *             length=255,
 *             unique=false,
 *             nullable=true
 *         )
 *     ),
 *     @AttributeOverride(name="usernameCanonical",
 *         column=@ORM'Column(
 *             name="usernameCanonical",
 *             type="string",
 *             length=255,
 *             unique=false,
 *             nullable=true
 *         )
 *     )
 * })
 * @ORM'Entity(repositoryClass="AppBundle'Repository'UserRepository")
 */
class User extends BaseUser
{
//..

当您运行php bin/console doctrine:schema:update --force时,它将使数据库中的用户名可以为null。

第二步,在您的表单类型AppBundle''form''RegistrationType中,从表单中删除用户名。

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->remove('username');
        // you can add other fields with ->add('field_name')
    }

现在,您将不会在表单中看到用户名字段(感谢$builder->remove('username');)。当你提交表单时,你不会再收到验证错误"请输入用户名",因为它不再是必需的(多亏了注释)。

来源:https://github.com/FriendsOfSymfony/FOSUserBundle/issues/982#issuecomment-12931663