Home > Software engineering >  show a list of users in symfony
show a list of users in symfony

Time:09-17

in my symfony project i have a function that shows a list of users based on their "roles" here's the controller code

/**
* @Route("/admin", name="admin_index", methods={"GET"})
*/
public function index(): Response
{
    $Admins=$this->getDoctrine()->getRepository(User::class)->findBy(['roles' => array('["ROLE_ADMIN"]')]);

    return $this->render('back/admin/index.html.twig', [
        'admins' => $Admins,
    ]);
}

and here's the render

<table class="table" >
    <thead>
        <tr>
            <th>Id</th>
            <th>Nom</th>
            <th>Email</th>
            <th>Tel</th>
            <th>Photo</th>
        </tr>
    </thead>
    <tbody>
    {% for admin in admins %}
        <tr name="elements" id="{{ 'admin'~ admin.id}}">
            <td>{{ admin.id }}</td>
            <td>{{ admin.nom }}</td>
            <td>{{ admin.email }}</td>
            <td>{{ admin.tel }}</td>
            <td><a href="{{ asset('/Uploads/Images/' ~ admin.photo) }}">{{ admin.photo }}</a></td>
            <td>
            </td>
        </tr>
    {% else %}
        <tr>
            <td colspan="10">Rien a afficher</td>
        </tr>
    {% endfor %}
    </tbody>
</table>

the problem here is that he's not showing anything even if the database is fulll

here's the entity declaration

 /**
 * @var string
 *
 * @ORM\Column(name="roles", type="json")
 * @Groups ("post:read")

 */
private $roles;

and here's a screenshot of table structure

enter image description here

i'm really stuck since the morning and i cant figure out why

CodePudding user response:

Since the roles field is json, your findBy won't work that way.

You should create a function in your UserRepository.php class to select users by their roles using QueryBuilder

    public function findByRole($role)
    {
        return $this->createQueryBuilder('u')
            ->andWhere('u.roles LIKE :role')
            ->setParameter('role', "%{$role}%")
            ->getQuery()
            ->getResult();
    }

you can then call that function from your controller

$admins = $this->getDoctrine()->getRepository(User::class)->findByRole("ROLE_ADMIN");

I also suggest you utilize var_dump($admins); in your controller to see if Doctrine is returning anything to you in the first place.

You can even dump variables in twig {{ dump(admins) }}

  • Related