Search code examples
symfonydoctrine-ormfosuserbundlepugxmultiuserbundle

How to get a list of users with specific role symfony controller


I'm new to symfony 2, working with FOSUserBundle along with PUGXMultiUserBundle and I have troubles retrieving the list of users with a specific role, for example : ROLE_ADMINISTRATEUR to notifiy them about something. Anyway, inspired by this this is my UserRepository class:

<?php
namespace OC\UserBundle\Entity;

use Doctrine\ORM\EntityRepository;


class UserRepository extends EntityRepository
{
 public function findByRoles($role)
{
 $qb = $this->_em->createQueryBuilder();
 $qb->select('u')
    ->from('OCUserBundle:User', 'u')
    ->where('u.roles LIKE :roles')
    ->setParameter('roles', '%"'.$role.'"%');

 return $qb->getQuery()->getResult();
 }
}

and this is the code inside in the controller's action:

$em=$this->getDoctrine()->getManager();
$repository2=$em->getRepository('OCUserBundle:User');
$roles='ROLE_ADMINISTRATEUR';
$users=$repository2->findByRoles(array('roles'=>$roles));

Return $this->render('OCUserBundle:Default:test.html.twig',array(
        'users'=>$users));

and my test.html.twig page:

 {% for a in users %}
 {{a.username}}
 {% endfor %}

All what I get is an empty page. Any help would be appreciated


Solution

  • Solved. Actually, using PUGXMultiUserBundle, you can select from a particular table, (you can associate a type of user with a role) so I changed the action inside the controller to this:

    $em=$this->getDoctrine()->getManager();
    $repository2=$em->getRepository('OCUserBundle:UserAdministrateur');
    $admins=$repository2->findAll();
    
    Return $this->render('OCUserBundle:Default:test.html.twig',array(
        'admins'=>$admins));
    

    Works like a charm. HOpe this helps someone.