首页 文章

如何从FOSUserBundle Symfony2.8中删除表单字段?

提问于
浏览
0

我在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 .

所以我需要更改任何其他文件以删除电子邮件领域的电子邮件验证?

谢谢 .

1 回答

  • 0

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

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

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

    class Author
    {
        /**
         * @Assert\NotBlank()           <--- remove this
         */
        public $name;
    }
    
    • 如果你扩展了类,你可以从你自己的成员定义中删除它 .

    • 如果你没有扩展它,扩展它然后不要放入验证约束 .

    • 或者其他一切都失败了(我认为这很麻烦),在调用 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);
    }
    

相关问题