Drupal - Tablesort with EntityQuery

Following some of the information found in Berdirs answer and comments I was able to arrive at a solution.

I formatted my header like so:

            $header = [
                'title'      => [
                    'data'      => t('title'),
                    'field'     => 'title',
                    'specifier' => 'title',
                ],
                'number'       => [
                    'data'      => t('Number'),
                    'field'     => 'field_number',
                    'specifier' => 'field_number',
                ],
                'time'       => [
                    'data'      => t('Time'),
                    'field'     => 'field_rank',
                    'specifier' => 'field_rank',
                ],
            ],

I then performed the EntityQuery like so

            $nids = \Drupal::entityQuery('node')
                ->tableSort($header)
                ->condition('type', 'my_content_type')
                ->condition('status', 1)
                ->pager($items_per_page)
                ->execute();

I formatted my rows like so

                $row = [
                    'data' => [
                        $node->title->value,
                        $node->field_number->value,
                        $node->field_rank->value,
                ];

After that generating the table was easy

            $render = [
                'table'           => [
                    '#prefix'        => '<h1>Entries</h1>',
                    '#theme'         => 'table',
                    '#attributes'    => [
                        'data-striping' => 0
                    ],
                    '#header' => $header,
                    '#rows'   => $rows,
                ],
            ];

The important parts I was missing is the proper format for $header. And using ->tableSort($header) instead of ->extend('Drupal\Core\Database\Query\TableSortExtender') ->orderByHeader($header) in my entityQuery


Entity query doesn't support extend() as you guessed and it also doesn't have any built in support for anything like Tablesort.

You should still be able to define the $header (your example is not correct, it needs to have a key for the field at least and optionally default sort order) and then use tablesort_get_order() and tablesort_get_sort() to get the field to sort on as well as the sort direction.

Edit: Turns out entity query does support that with tableSort(), but as I said, your header definition is not correct, see comments.

Tags:

Database