角色界面和管理角色 [英] Role Interface and Manage Roles

查看:21
本文介绍了角色界面和管理角色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有简单的 UserInterface 实体:

I have simple UserInterface entity:

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

与Role Entity接口的多对多关系

and with many to many relation with Role Entity interface

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

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

When I try to manage user roles with form Type

public function buildForm(FormBuilder $builder, array $options)
{
    $builder->add('roles');
}

Symfony 返回一个错误:

Symfony returns me an error:

类型为Doctrine\Common\Collections\Collection"的预期参数,给定数组"

Expected argument of type "Doctrine\Common\Collections\Collection", "array" given

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

I know the error is in the getRoles method of the entity User that returns an array but I also know getRoles is a method of the interface and must return an array!

有人有好的解决方案吗?

Anyone have a good solution?

推荐答案

你有两个 getRoles 函数:

You have two getRoles functions:

  • 一个是返回角色列表的 UserInterface 接口函数
  • 另一个是 $roles 属性的 getter

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

Since both functions cannot be called the same and they cannot be the same function because they need to return different types, and since the first function needs to follow the interface I suggest you change the name of the second function. Since this needs to reflect the name of the property, you should change this name.

因此,您需要执行以下操作:

So, you need to do something like:

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

/* interface */

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

/*getter*/

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

然后

public function buildForm(FormBuilder $builder, array $options)
{
    $builder->add('userRoles');
}

这篇关于角色界面和管理角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆