I created a Drupal custom module that grabs information from an array and then displays the information in a table. I'm trying to make the headers of the table sortable. The issue I'm having is the information is not stored in the database and all of the examples I'm seeing uses the SQL to sort the table.
Here is what I have so far, this currently displays the table, in the $header I added the 'sort' which creates the sort button on the table but obviously doesn't work.
I know I can use TableSort, but that's where I'm having trouble.
<?php
namespace Drupal\documents\Controller;
use Drupal\Core\Controller\ControllerBase;
class DocumentsNotesController extends ControllerBase {
public function documents(){
$header = [
['data' => t('Date'), 'field' => 't.date'],
['data' => t('Category'), 'field' => 't.category'],
['data' => t('Name'), 'field' => 't.name', 'sort' => 'desc'],
];
//The commented out sections below don't work, I'm assuming I need to include?
// getting the current sort and order parameters from the url
//$order = tablesort_get_order($headers);
//$sort = tablesort_get_sort($headers);
// sort the table data accordingly (write your own sort function)
//$tableData = my_array_sort($tableData, $order['sql'], $sort);
$newPath = '/my-path-here-to-grab-docs';
$rows = array();
foreach(glob($newPath) as $file) {
//Doing a bunch of logic here, that's not necessary to display in forum.
$rows[] = [
'date' => $date,
'category' => $category,
'name' => $name,
];
}
// Create the table as a render array.
$content[] = [
'#theme' => 'table',
'#header' => $header,
'#rows' => $rows,
'#empty' =>t('No files found'),
'#attributes' => array (
'class' => array('table table-striped'),
),
];
return $content;
}
}
For reference here is some documents I was looking at: https://drupal.stackexchange.com/questions/238930/how-to-use-an-entity-query-to-make-a-sortable-table
https://drupal.stackexchange.com/questions/14889/can-tablesort-be-used-without-a-query/110576
https://zanzarra.com/blog/drupal-custom-pager-and-table-header-sortable-without-sql-query