如何覆盖注册表单Fos用户和选择字段填充角色SYMFONY2

时间:2011-11-19 20:14:50

标签: symfony fosuserbundle

我按照文档覆盖FosUser的注册表单,然后显示我想要的角色。这是我的注册表。

<?php

namespace My\BlogBundle\Form;
use My\BlogBundle\Entity\User; 
use Symfony\Component\Form\FormBuilder;
use FOS\UserBundle\Form\Type\RegistrationFormType as BaseType;

class MyRegisterType extends BaseType
{
 public function buildForm(FormBuilder $builder, array $options)
 {
    parent::buildForm($builder ,$options);
    $user = new User();
    $builder
        ->add('roles' ,'choice' ,array('choices'=>$user->getRoles() ) ;

 }

 public function getName()
 {
    return 'my_register_type';
 }
}

这是我的用户实体。

<?php

namespace My\BlogBundle\Entity;

use FOS\UserBundle\Entity\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;

/**
* My\BlogBundle\Entity\User
*
* @ORM\Table()
* @ORM\Entity(repositoryClass="My\BlogBundle\Entity\UserRepository")
*/
class User  extends BaseUser
{
 /**
  * @var integer $id
  * 
  * @ORM\Column(name="id", type="integer")
  * @ORM\Id
  * @ORM\GeneratedValue(strategy="AUTO")
  */
 protected $id;

 protected $roles=array();




/**
 *@ORM\OneToMany(targetEntity="Article" ,mappedBy="user")
 */
protected $article;

/**
 *@ORM\OneToMany(targetEntity="Comment" ,mappedBy="user")
 */
protected $comment;

 public function __construct()
 {
    parent::__construct();
    $this->roles=array('searcher' ,'annoucer');
 }

}

我现在的问题是我不知道如何在该字段上仅显示我添加的角色,因为我也获得了ROLE_USER选项,当我提交表单时出现此错误

Catchable Fatal Error: Argument 1 passed to FOS\UserBundle\Model\User::setRoles() must be an array, string given, called in /var/www/blog/vendor/symfony/src/Symfony/Component/Form/Util/PropertyPath.php on line 346 and defined in /var/www/blog/vendor/bundles/FOS/UserBundle/Model/User.php line 709

任何帮助都不仅仅是值得赞赏,谢谢。顺便说一句,对不起,我无法添加其他标签:P

2 个答案:

答案 0 :(得分:4)

我认为您的问题是因为您使用的是ChoiceField。 ChoiceField将只返回一个角色(字符串类型,角色的此ID),但方法setRoles期望一个数组。这意味着您需要添加选项multiple => true或更改为其他类型的字段,例如Collection字段。使用multiple将返回setRoles接受的数组,并使用Collection字段也会返回数组。

从底线开始,您需要选择一个返回数组而不是单个结果的表单字段,即字符串。您可以看到所有表单类型here

希望这有帮助。

答案 1 :(得分:1)

我也有同样的问题,然后我在控制器中使用这行代码来解决它。

  

在您的注册表中

->add('roles', 'choice', array(
                'mapped' => false,
                'required' => true,
                'label'    => 'User Type',
                'choices' => array(
                    'ROLE_USER' => 'User',
                    'ROLE_STAFF' => 'Staff',
                    'ROLE_INSTITUTE' => 'Institute',
                ),
                'expanded'   => true,
            ))
  

并在控制器中

    $role = $form->get('roles')->getData();
    $user->setRoles(array($role));
    $em->persist($user);
    $em->flush();