Question

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

Était-ce utile?

La solution

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>

Autres conseils

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').

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top