symfony2多对多的实体形式

时间:2012-05-24 20:48:37

标签: forms authentication symfony many-to-many

我有两个人User Role。两者都在Symfony2中用于身份验证。验证过程需要在类User中有方法'getRoles',它返回数组。 另一方面,有一个表单构建器需要以Collection形式给出的角色。 我如何强制表单构建器使用特定的getter来获取角色集合?

 class UserType extends AbstractType{
 //...
 ->add('roles', 'entity', array( 'class' => 'MyBundle:Role',
                                    'property' => 'name',
                                    'required' => false, 
                                    'multiple' => true,
                                    'expanded' => true,
                                    );

 //...
  }


 class User implements UserInterface {
 //...
    public function getRoles() {
    return $this->roles->toArray();  //This needs authentication mechanism
   }

 public function getRolesCollection() {
    return $this->roles;            //This needs form builder.
}
 //...
 }

1 个答案:

答案 0 :(得分:0)

也许你可以尝试将其全部反转:

class UserType extends AbstractType{
 //...
 ->add('rolesCollection', 'entity', array( 'class' => 'MyBundle:Role',
                                    'property' => 'name',
                                    'required' => false, 
                                    'multiple' => true,
                                    'expanded' => true,
                                    );

 //...
  }


 class User implements UserInterface {
  protected $rolesCollection
 //...
    public function getRoles() {
    return $this->rolesCollection->toArray();  //This needs authentication mechanism
   }

 public function getRolesCollection() {
    return $this->rolesCollection;            //This needs form builder.
}
 //...
 }