Last active
August 11, 2022 16:30
-
-
Save ozin7/ceacd29cf7db4115c2346b1b63874ef9 to your computer and use it in GitHub Desktop.
Drupal 8/9: Add sorting and pager to the Database connection query
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks, it helped a lot!