【问题标题】:How to remove Form Field From FOSUserBundle Symfony2.8?如何从 FOSUserBundle Symfony2.8 中删除表单字段?
【发布时间】:2017-01-10 10:52:50
【问题描述】:

我已经在我的 Symfony 项目中安装了 FOSUserBundle。现在我想删除 FOSUserBundle 默认提供的注册表单字段。

注册表单字段是:

用户名

电子邮件 ID

密码

重复密码

现在我不想在用户注册时使用 Email 字段,因此我覆盖了我的捆绑包中的注册表单。

\\ Front\FrontBundle\Form\RegistrationType.php
<?php
namespace Front\FrontBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

class RegistrationType extends AbstractType
{

    public function buildForm(FormBuilderInterface $builder, array $options)
   {
      $builder->remove('email'); // here I code for remove email field.
   }



   public function getParent()
  {
    return 'FOS\UserBundle\Form\Type\RegistrationFormType';

    // Or for Symfony < 2.8
    // return 'fos_user_registration';
  }

  public function getBlockPrefix()
  {
    return 'app_user_registration';
  }

   // For Symfony 2.x
  public function getName()
  {
    return $this->getBlockPrefix();
  }

}

然后我更改 config.yml 和 services.yml 文件

\\ App/config/config.yml

fos_user:
db_driver: orm 
firewall_name: main
user_class: Front\FrontBundle\Entity\User
registration:
    form:
        type: Front\FrontBundle\Form\RegistrationType




\\app/config/services.yml
services:
app.form.registration:
    class: Front\FrontBundle\Form\RegistrationType
    tags:
        - { name: form.type, alias: app_user_registration }  

所以在完成此电子邮件字段后,从我的注册表中删除,但是当我在填写 usernamepasswordrepeat password 后提交表单时,它会给我任何 The email is not valid 的错误。

所以我需要更改任何其他文件以删除带有电子邮件字段的电子邮件验证?

谢谢。

【问题讨论】:

  • email 是 FOSUser 提供给您扩展的模型的必填字段。如果你不想要它,就不要扩展 FOS\UserBundle\Model\User。
  • @Federico 你能详细解释一下吗?我需要更改哪个文件?
  • 由于email 是在 FOSUserBundle 提供的抽象中定义的,因此您几乎不得不使用它。我相信简单的解决方案是覆盖模型的 setUsername 方法,并在此处设置一个假的(有效且唯一的)电子邮件。
  • 但是如果您不需要 FOSUserBundle 提供的大部分功能,就不要使用它

标签: symfony fosuserbundle


【解决方案1】:

您可以像以前一样删除该字段,但您必须确保没有需要它的剩余服务器端验证。

如何做到这一点取决于您如何扩展 FOS 用户类(或者如果您有)。

例如,带注释的约束看起来像这样(来自the docs

class Author
{
    /**
     * @Assert\NotBlank()           <--- remove this
     */
    public $name;
}
  • 如果您扩展了该类,您可以将其从您自己的成员定义中删除。
  • 如果你没有扩展它,扩展它然后不要加入验证约束。
  • 或者其他一切都失败了(我认为这是 hacky),在调用 isValid() 之前在控制器中发出一个默认值。

    public function someAction(Request $request) {
        // ...
    
        $user = new User();
    
        // fill empty value
        $user->setEmail('blank@blank.blank');
    
        // form stuff here
        // ...
        if ($form->isValid()) {
            // do some stuff
        }
    
        return $this->render(blahblahbal);
    }
    

【讨论】:

  • 我没有得到你的答案。我认为你是对的,但你能告诉我我可以把你的代码放在哪里吗?我不需要更改任何控制器文件。我只是覆盖注册表单并添加代码以删除提交的电子邮件现在我想删除来自 FOSUserBundle 的电子邮件字段的验证,这样我就可以在没有电子邮件字段的情况下注册用户。现在,当我提交“此电子邮件无效”的表单时出现错误,但我的字段未显示。
  • 它是你需要扩展User.php的实体文件。如果你不能/不想你必须编辑控制器。它没有显示,这是你想要的,但 symfony 仍然认为它是空的,它被告知要验证它。
猜你喜欢
  • 2017-08-31
  • 2016-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-12
  • 1970-01-01
  • 2020-03-10
  • 1970-01-01
相关资源
最近更新 更多