I am trying to get only user with ROLE_USER
.
I have this in my controller:
$query = $this->getDoctrine()->getEntityManager()
->createQuery(
'SELECT u FROM StageUserBundle:User u WHERE u.roles LIKE :role'
)->setParameter('role', '%"ROLE_USER"%'
);
$users = $query->getResult();
It worked with ROLE_ADMIN
instead of ROLE_USER
but I need to show only User.getRoles()== "ROLE_USER"
.
Your problem is that the User model in FOSUserBundle never actually has the ROLE_USER
.
FOS\UserBundle\Model\UserInterface
const ROLE_DEFAULT = 'ROLE_USER';
FOS\UserBundle\Model\User
public function addRole($role)
{
$role = strtoupper($role);
if ($role === static::ROLE_DEFAULT) {
return $this;
}
if (!in_array($role, $this->roles, true)) {
$this->roles[] = $role;
}
return $this;
}
....
public function getRoles()
{
$roles = $this->roles;
foreach ($this->getGroups() as $group) {
$roles = array_merge($roles, $group->getRoles());
}
// we need to make sure to have at least one role
$roles[] = static::ROLE_DEFAULT;
return array_unique($roles);
}
When you getRoles
it add the ROLE_USER
as a default and when you addRole
it check to see if the role is ROLE_USER
and then skips if it does.
In reality every user on your system will have the ROLE_USER
so to find all users with the role you can just do a SELECT u FROM StageUserBundle:User u
.
I Found the solution to my problem . i changed this in my controller :
$query = $this->getDoctrine()->getEntityManager()
->createQuery('SELECT u FROM StageUserBundle:User u WHERE NOT u.roles LIKE :role'
)->setParameter('role', '%"ROLE_ADMIN"%' );
$users = $query->getResult();
Hope this will help.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With