TableSortExampleController.php
Namespace
Drupal\tablesort_example\Controller
File
-
modules/tablesort_example/src/Controller/TableSortExampleController.php
View source
<?php
namespace Drupal\tablesort_example\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Database\Connection;
use Symfony\Component\DependencyInjection\ContainerInterface;
class TableSortExampleController extends ControllerBase {
protected $database;
public static function create(ContainerInterface $container) {
$controller = new static($container->get('database'));
$controller->setStringTranslation($container->get('string_translation'));
return $controller;
}
public function __construct(Connection $database) {
$this->database = $database;
}
public function description() {
$header = [
[
'data' => $this->t('Numbers'),
'field' => 't.numbers',
],
[
'data' => $this->t('Letters'),
'field' => 't.alpha',
],
[
'data' => $this->t('Mixture'),
'field' => 't.random',
],
];
$query = $this->database
->select('tablesort_example', 't')
->extend('Drupal\\Core\\Database\\Query\\TableSortExtender');
$query->fields('t');
$result = $query->orderByHeader($header)
->execute();
$rows = [];
foreach ($result as $row) {
$rows[] = [
'data' => (array) $row,
];
}
$build = [
'#markup' => '<p>' . $this->t('The layout here is themed as a table that is sortable by clicking the header name.') . '</p>',
];
$build['tablesort_table'] = [
'#theme' => 'table',
'#header' => $header,
'#rows' => $rows,
];
return $build;
}
}
Classes