How to get Pagination direction in twig for KNP paginator?
Asked Answered
M

2

6

I am using knp paginator and it works well but when I want to use its sorting feature I have problem to get the sort direction in twig.

the following code is indicate how to get the sorted table header but not taking about how to get sorted table header direction.

{# total items count #}
<div class="count">
    {{ pagination.getTotalItemCount }}
</div>
<table>
<tr>
{# sorting of properties based on query components #}
    <th>{{ knp_pagination_sortable(pagination, 'Id', 'a.id') }}</th>
    <th{% if pagination.isSorted('a.Title') %} class="sorted"{% endif %}>{{ knp_pagination_sortable(pagination, 'Title', 'a.title') }}</th>
</tr>

{# table body #}
{% for article in pagination %}
<tr {% if loop.index is odd %}class="color"{% endif %}>
    <td>{{ article.id }}</td>
    <td>{{ article.title }}</td>
</tr>
{% endfor %}
</table>
{# display navigation #}
<div class="navigation">
    {{ knp_pagination_render(pagination) }}
</div>

I get this code from KnpPaginator documentation on following link: https://github.com/KnpLabs/KnpPaginatorBundle

Mafalda answered 17/11, 2013 at 7:26 Comment(0)
C
9

You should be able to just use {{ pagination.getDirection() }} in your twig template to find the current sort direction (if any) then set up your classes based on that.

{% set direction = pagination.getDirection() %}
<th{% if pagination.isSorted('p.id') %} class="sorted {{ direction }}"{% endif %}>
    {{ knp_pagination_sortable(pagination, 'Id', 'p.id') }}
</th>

But... as of this post, KNP has not yet merged this fix: https://github.com/sroze/KnpPaginatorBundle/commit/3105a38714c6f89c590e49e9c50475f7a777009d

When there is no direction parameter set, the current Paginator bundle throws an error.

So, until the above fix is merged, you can still get the direction with a bit more verbosity:

{% set directionParam = pagination.getPaginatorOption('sortDirectionParameterName') %}
{% set params = pagination.getParams() %}
{% set direction = params[directionParam] is defined ? params[directionParam] : null %}
<th{% if pagination.isSorted('p.id') %} class="sorted {{ direction }}"{% endif %}>
    {{ knp_pagination_sortable(pagination, 'Id', 'p.id') }}
</th>
Comose answered 11/4, 2014 at 18:49 Comment(0)
O
4

When you call {{ knp_pagination_sortable(pagination, 'Id', 'a.id') }}, bundle automatically generates link with a class holding an information about sort direction, which looks something like this: <a translationcount="" class="asc" href="?sort=a.id&direction=desc&page=1" title="Id">Id</a> So just put this class in your css file and style it with the arrow. If you, for some reason, need to get a sort direction inside a controller, just read it from request $request->query->get('direction').

Oversweet answered 20/11, 2013 at 8:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.