1

我有两个实体User Role。两者都在 Symfony2 中用于身份验证。身份验证过程需要在返回数组的 User 类中具有方法“getRoles”。另一方面,表单构建器需要以集合形式给出的角色。我如何强制表单生成器使用特定的 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.
}
 //...
 }
4

1 回答 1

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.
}
 //...
 }
于 2012-05-24T23:12:17.997 回答