2011-11-19 19 views
4

我按照文檔覆蓋FosUser的註冊表格,並顯示我想要的角色。這是我的註冊表格。如何覆蓋寄存器形式FosUser和選擇字段帶角色的函數SYMFONY2

<?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 

任何幫助將不勝感激,謝謝。 BTW對不起,我無法添加其他標籤:P

回答

4

我認爲你的問題是因爲你使用的是ChoiceField。一個ChoiceField將只返回一個角色(一個字符串類型,這個角色的id),但方法setRoles期望一個數組。這意味着您需要添加選項multiple => true或更改爲其他類型的字段,如Collection字段。使用multiple將返回一個將被setRoles接受的數組,並且使用Collection字段也將返回一個數組。

底線,你需要選擇一個表單字段,返回一個數組而不是單個結果,一個字符串。你可以看到所有表單類型here

希望這會有所幫助。

+0

好感謝球員虐待測試出來,讓你硝酸鉀感謝 – kosaidpo

+0

你好,大家好我測試了它出來,不幸的是,這不是我想要的,我想讓用戶選擇他的(帳戶類型是他的角色是)尋找工作的人,任何其他解決方法?謝謝 – kosaidpo

+1

然後你必須保持你的表單類型,即'ChoiceField',但是需要重寫FOSUserBundle類並創建一個名爲'setRole'的方法,它將接收一個字符串,你想設置的角色的id。然後,當你的類型添加到你的表單中,而不是使用'roles'時,你使用'role',表單組件將用單個值調用'setRole'。 – Matt

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();