Drupal core has the Drupal\Core\Utility\TableSort class which can be used to create tables with sortable columns. All examples in core however are based on Drupal\Core\Database\Query\TableSortExtender which providers table sorting for data coming from a database query.

I am looking to display data that is generated by custom code and is not originating from a query. How can I use the TableSort code directly in my controller?

This is the Drupal 8 version of the same question for Drupal 7. See the answers there for additional insights.

1 Answer 1


TableSort has methods to retrieve the sorting order and the field being sorted directly from the query arguments. You can use the values returned by ::getSort() and ::getOrder() to do a custom sorting of your data.

In your render array you can use some (undocumented) options in the #header declaration to control the way the table is initially sorted:

  • field: the name to use in the query arguments to indicate that the table should be sorted by this column.
  • sort: one (and only one) of the columns can be given this option (with value either asc or desc). This will be the column that is sorted by default.
  • initial_click_sort: this can be set to desc if the data should be sorted in descending order if the column header is initially clicked. This defaults to asc but for some data you want to show larger numbers at the top by default.

Here is an example of a controller using data from a custom array:


declare(strict_types = 1);

namespace Drupal\my_project\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Utility\TableSort;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RequestStack;

 * Demo of a table with sortable columns using data from a custom source.
class SortableTableDemoController extends ControllerBase {

   * The Symfony request stack.
   * @var \Symfony\Component\HttpFoundation\RequestStack
  protected $requestStack;

   * Constructs a new SortableTableDemoController.
   * @param \Symfony\Component\HttpFoundation\RequestStack $requestStack
   *   The request stack.
  public function __construct(RequestStack $requestStack) {
    $this->requestStack = $requestStack;

   * {@inheritdoc}
  public static function create(ContainerInterface $container): self {
    return new static(

   * Returns a render array containing data about Linux distributions.
   * @return array
   *   The render array.
  public function linuxDistributionsTable(): array {
    $headers = [
      // The distribution label has the 'sort' option, making it the default.
        'data' => $this->t('Distribution'),
        'field' => 'label',
        'sort' => 'asc',
        'data' => $this->t('Initial release'),
        'field' => 'year',
      // Sorted from highest to lowest on initial click.
        'data' => $this->t('Packages'),
        'field' => 'packages',
        'initial_click_sort' => 'desc',

    $data = [
      ['label' => 'Arch Linux', 'year' => 2002, 'packages' => 77264],
      ['label' => 'Debian', 'year' => 1993, 'packages' => 118326],
      ['label' => 'Red Hat', 'year' => 2002, 'packages' => 12155],
      ['label' => 'Gentoo Linux', 'year' => 2002, 'packages' => 29092],
      ['label' => 'OpenSUSE', 'year' => 2006, 'packages' => 76236],
      ['label' => 'Ubuntu', 'year' => 2004, 'packages' => 89403],

    // Sort the table according to the options passed in the query arguments.
    $request = $this->requestStack->getCurrentRequest();
    $sort = TableSort::getSort($headers, $request);
    $order_by = TableSort::getOrder($headers, $request)['sql'];

    usort($data, function (array $a, array $b) use ($sort, $order_by): int {
      $result = $a[$order_by] <=> $b[$order_by];
      return $sort === 'asc' ? $result : -$result;

    return [
      'table' => [
        '#type' => 'table',
        '#header' => $headers,
        '#rows' => $data,


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.