Major Productions
Major Productions

Reputation: 6042

Doctrine and FOSUserBundle - displaying users according to their roles

I need to be able to display all ROLE_ADMIN and ROLE_SUPER_ADMIN users in a paginated table. I have the table displaying everyone correctly using Doctrine's findBy() method, but I'm a bit stumped on how to filter by role. Roles are saved as a DC2Type:array, and the role data itself looks a bit like JSON:

a:1:{i:0;s:9:"ROLE_USER";}

With that, I'm curious as to what to pass into findBy() to select all ROLE_ADMIN and ROLE_SUPER_ADMIN users.

In other words:

$users = $em->getRepository('Acme\SiteBundle\Entity\User')->findBy(array(/* what do I put here? */), array('id' => 'asc'), $perPage, $perPage * ($page - 1));

EDIT: Hmm... it looks like findBy() may not be the way to go here after all. D'oh!

Upvotes: 0

Views: 1080

Answers (2)

Emii Khaos
Emii Khaos

Reputation: 10085

I think coupling each role in a group and working with groups would be much more better. Specially assign and decline roles groups gets easier as it's a simple relation. Also query for a specfic group gets easy.

Upvotes: 3

moonwave99
moonwave99

Reputation: 22817

That notation is the serialization of a PHP array - this means that FOSUserBundle does not normalize the user-roles relationship.

But you can provide you own user class and overload the roles getters/setters, or if you don't have to deal with that many users, you can overload the user repository by fetching all users and filtering by role.

A dirty hack would be to issue a LIKE search on the roles field, as the role name is still readable, but it would be kind of bad performance wise.

You can find more info in this repository issue.

Upvotes: 2

Related Questions