0

I have a table of users. and I need to be able to filter them by 'Group'. So when user selects option from drop-down list, I want not the whole page but only users table to reload and display users from that group

This is twig for users table

  Filter by group
  <select class="filter-users">
         <option selected></option>
         {% for group in groups %}
                <option>{{ group.name }}</option>
         {% endfor %}
   </select>
   <table id="dataTable">
         <tbody>
             {% for user in users %}
                  <tr>
                    <td>{{user.id}}</td>
                    <td>{{user.fullName}}</td>
                    </tr>
              {% endfor %}
           </tbody>
       </table>

This action to get users by group name

 /**
  * @Route("/filter", name="users_filter")
  */
  public function filterAction(Request $request)
  {
    $em = $this->getDoctrine()->getManager();

    $group = $request->request->get('group');

    $users = $em->getRepository('AppBundle:User')->findBy(['group' => group]);

    return $this->render('AppBundle:User:list.html.twig', [
        'users' => $users
    ]);
}
2

1 Answer 1

0

If you want only the table to be reloaded you could do the following.

First create a template only with the table.

table.html.twig

       <table id="dataTable">
         <tbody>
             {% for user in users %}
                  <tr>
                    <td>{{user.id}}</td>
                    <td>{{user.fullName}}</td>
                    </tr>
              {% endfor %}
           </tbody>
       </table>

In controller

public function indexAction(Request $request)
    {
       $em = $this->getDoctrine()->getManager();

       $group = $request->request->get('group');

       $users = $em->getRepository('AppBundle:User')->findBy(['group' => group]

       return new Response($this->renderView('table.html.twig', [
           'users' => $users,
       ]));
    } 

Then create an ajax call

$('#select-button-div').on('change','#select-button',function() {
    reloadData();
});

function reloadData() {
        let data = {};
        let selected = $('#select-button').find(':selected').text();
        let usersTable = $('#entries');
        usersTable.empty();
        data['selectedVal'] = selected.val();
        let url = Routing.generate('ToYourRoute');
        table.load(url, data);
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.