Skip to content

Instantly share code, notes, and snippets.

@ozin7
Last active August 11, 2022 16:30
Show Gist options
  • Save ozin7/ceacd29cf7db4115c2346b1b63874ef9 to your computer and use it in GitHub Desktop.
Save ozin7/ceacd29cf7db4115c2346b1b63874ef9 to your computer and use it in GitHub Desktop.
Drupal 8/9: Add sorting and pager to the Database connection query
<?php
use Drupal\Core\Database\Query\PagerSelectExtender;
use Drupal\Core\Database\Query\TableSortExtender;
// Field = column name in your table.
$header = [
'status' => ['data' => $this->t('Order status'), 'field' => 'status'],
'order_id' => ['data' => $this->t('Order number'), 'field' => 'order_id', 'sort' => 'desc'],
'placed' => ['data' => $this->t('Order date'), 'field' => 'placed'],
'seller' => ['data' => $this->t('Seller'), 'field' => 'seller'],
'total' => ['data' => $this->t('Total amount'), 'field' => 'total'],
'',
];
$table = [
'#theme' => 'table',
'#rows' => [],
'#header' => $header,
'#empty' => $this->t('You have not placed any orders with us yet.'),
'#attributes' => [
'class' => [
'order-history',
],
],
];
$query = \Drupal::database()->select(self::TABLE_NAME, 'cso')
->fields('cso')
->condition('cs_number', 21);
$query = $query->extend(PagerSelectExtender::class)->limit(10);
$query = $query->extend(TableSortExtender::class)->orderByHeader($header);
$order_records = $query->execute()->fetchAll();
@mialdi98
Copy link

Thanks, it helped a lot!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment