-->

Role Interface and Manage Roles

2020-07-30 02:01发布

问题:

I have simple UserInterface entity:

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

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 returns me an error:

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

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?

回答1:

You have two getRoles functions:

  • One is the function for the UserInterface interface which returns a list of Roles
  • The other is the getter for your $roles property

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;
}

and then

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