Sorting with Twig and KnpPaginatorBundle
In this video you will see how quickly you can add Sorting to your Twig CRUD implementation thanks to the KNP Paginator Bundle's
knp_pagination_sortable template helper.
Sorting in this instance is the act of arranging specific fields of data in Ascending, or Descending order.
By default, our data will be returned with an implicit sort on the
id field, with the records in an ascending order. This is technobabble for saying we start with
id 1, and go up until we reach, in our case,
id 50. The 'implicit' part of this statement says that we don't need to explicitly state we want to sort by
id ascending, it is simply implied.
Changing the field to sort on, and / or the sorting direction is simply a case of tweaking the URL:
And so on.
knp_pagination_sortable helper function figures out how the URL should look for us.
This is really nice and super easy to add.
But there's another point to this.
We will be re-using the KNP Paginator Bundle in our API implementation. Therefore, our URLs will look and act identically.
You are - of course - free to change the query parameter names for any of these fields. This is done in the configuration we added when installing the bundle:
# /app/config/config.yml knp_paginator: default_options: page_name: page # page query parameter name sort_field_name: sort # sort field query parameter name sort_direction_name: direction # sort direction query parameter name
This might be useful if you are internationalising your implementation in some way, but for the most part, the defaults do a good enough job.
There's really not much more that we need to know to make use of this. It just works :)