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.

The 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

        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 :)

Code For This Episode

Get the code for this episode.

Share This Episode

If you have found this video helpful, please consider sharing. I really appreciate it.

Episodes in this series

# Title Duration
1 Intro, and Project Demo 02:27
2 Pagination with Twig and KnpPaginatorBundle 07:49
3 Sorting with Twig and KnpPaginatorBundle 02:15
4 Simple Filtering in Twig 05:00
5 API - Pagination, (Basic) Filtering, and Sorting 10:25
6 Angular - Pagination 10:14
7 Angular - Sorting 06:11
8 Angular - Limiting 05:43
9 Angular - Filtering 03:47
10 React - Pagination (Part 1) 10:45
11 React - Pagination (Part 2) 04:14
12 React - Sorting 11:11
13 React - Limiting 03:43
14 React - Filtering 03:41