Search code examples
symfonyknppaginator

How to avoid reloading form when using knpPaginator


I have a search bar to find molecules by name to then show all the molecules containing this name just under the search bar on the same page.

I have added knpPaginator and it works perfectly but when I go to next page I have to reload the form and it shows the next molecules.

My question is: Is there a way to avoid form reload? I can show the results in another page but i'd prefer to keep it like this:

i show you my conControler :

$form = $this->createForm('NcstoxBundle\Form\FindMolNameType');
    $form->handleRequest($request);
    $em = $this->getDoctrine()->getManager();
    $molecules = $em->getRepository('NcstoxBundle:Molecule')->findAll();

    if ($form->isSubmitted() && $form->isValid()) {
        $data = $form->getData();
        $molecules = $em->getRepository('NcstoxBundle:Molecule')->findByMolName($data);

        $paginator  = $this->get('knp_paginator');
        $pagination = $paginator->paginate(
            $molecules, /* query NOT result */
            $this->get('request')->query->getInt('page', 1)/*page number*/,
            10/*limit per page*/
        );

        return $this->render('NcstoxBundle:Default:molNameResult.html.twig', array(
            'form' => $form->createView(),
            'molecules' => $molecules,
            'pagination' => $pagination
        ));
    }

my view :

<div class="search">
    <h3>Make a Search by Molecule Name :</h3>
    {{ form_start(form) }}
    {{ form_widget(form, {'attr': {'title': 'test'}}) }}
    <input class="btn btn-primary" type="submit" value="Search">
    {{ form_end(form) }}
</div>
<h3>Search Results :</h3>
<div class="count">
    {{ pagination.getTotalItemCount }} Molecules
</div>
<table class="table table-hover table-condensed">
    <thead>
    <tr>
        <th>{{ knp_pagination_sortable(pagination, 'Name', 'a.name') }}</th>
    </tr>
    </thead>
    <tbody>
    {% for molecule in pagination %}
        <tr>
            <td><a href="{{ path('molSheet', {'id':molecule.id}) }}">{{ molecule.mainName }}</a></td>
        </tr>
    {% else %}
        <tr>
            <td>There isn't molecule corresponding to your query</td>
        </tr>
    {% endfor %}
    </tbody>
    <tfoot></tfoot>
</table>
<div class="navigation fin taille">
    {{ knp_pagination_render(pagination) }}
</div>

Please be indulgent, StackOverflow says that i'm in danger to be blocked and I'm French so English is not my primary language.


Solution

  • KnpPaginatorBundle have a 'secret' (undocumented) filter.

    You don't need to do the form yourself, just apply it in your template as :

    {{ knp_pagination_filter(pagination, {'a.name': 'Name'}) }}

    KnpPaginator will then manage the filtering.

    For more informations you can take a look here : https://github.com/KnpLabs/KnpPaginatorBundle/issues/225

    Hope it helps :)