角色界面和管理角色

Mau*_*uro 1 symfony symfony-2.1

我有简单的UserInterface实体:

function getRoles()
{
    return $this->roles->toArray();
}
Run Code Online (Sandbox Code Playgroud)

与Role Entity接口有很多很多关系

/**
* @ORM\ManyToMany(targetEntity="Role", inversedBy="users", cascade={"persist"})
*/
protected $roles;
Run Code Online (Sandbox Code Playgroud)

当我尝试使用表单类型管理用户角色时

public function buildForm(FormBuilder $builder, array $options)
{
    $builder->add('roles');
}
Run Code Online (Sandbox Code Playgroud)

Symfony给我一个错误:

期望参数类型为"Doctrine\Common\Collections\Collection","array"

我知道错误是在实体User的getRoles方法中返回一个数组,但我也知道getRoles是接口的一个方法,必须返回一个数组!

谁有一个很好的解决方案?

Car*_*dos 5

你有两个getRoles函数:

  • 一个是UserInterface接口的函数,它返回一个Roles列表
  • 另一个是你的$ roles属性的getter

由于两个函数不能被调用相同而且它们不能是相同的函数,因为它们需要返回不同的类型,并且由于第一个函数需要遵循接口我建议你更改第二个函数的名称.由于这需要反映属性的名称,因此您应该更改此名称.

所以,你需要做一些事情:

/**
 * @ORM\ManyToMany(targetEntity="Role", inversedBy="users", cascade={"persist"})
 */
protected $userRoles;

/* interface */

function getRoles()
{
    return $this->userRoles->toArray();
}

/*getter*/

function getUserRoles() {
    return $this->userRoles;
}
Run Code Online (Sandbox Code Playgroud)

然后

public function buildForm(FormBuilder $builder, array $options)
{
    $builder->add('userRoles');
}
Run Code Online (Sandbox Code Playgroud)