-
-
Save linuslundahl/3863543 to your computer and use it in GitHub Desktop.
Drupal table with pager from db_select()
This file contains 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 | |
/** | |
* Display point award report. | |
* | |
* Generates a list of awarded points. | |
* | |
* @return array $content | |
*/ | |
function game_report_page_points() { | |
$header = array( | |
'id' => array('data' => t('ID'), 'field' => 'id'), | |
'points' => array('data' => t('Points'), 'field' => 'points'), | |
'point_name' => array('data' => t('Type'), 'field' => 'point_name'), | |
'point_category' => array('data' => t('Category'), 'field' => 'point_category'), | |
'timestamp' => array('data' => t('Date'), 'field' => 'timestamp'), | |
'meta' => array('data' => t('Meta'), 'field' => 'meta'), | |
'name' => array('data' => t('User'), 'field' => 'name'), | |
); | |
// For some mysterious reason only parts of the db_select API is chainable. | |
// Which means that sometimes you have to split it up like I've done below. | |
$query = db_select('game_points', 'p') | |
->extend('PagerDefault') | |
->extend('TableSort') | |
->limit(50) | |
->orderByHeader($header); | |
$query->join('users', 'u', 'p.uid = u.uid'); | |
$query->fields('p', array( | |
'id', | |
'points', | |
'point_name', | |
'point_category', | |
'timestamp', | |
'meta', | |
)); | |
$query->fields('u', array('name')); | |
$result = $query->execute()->fetchAllAssoc('id'); | |
$render = array( | |
'table' => array( | |
'#theme' => 'table', | |
'#header' => $header, | |
'#rows' => array_map(function ($row) { | |
return (array)$row; | |
}, $result), | |
'#sticky' => TRUE, | |
'#empty' => t('No points recorded yet.'), | |
), | |
'pager' => array( | |
'#theme' => 'pager', | |
), | |
); | |
_game_preprocess_report($render); | |
return $render; | |
} | |
/** | |
* Preproccsing of report tables. | |
* | |
* @param array $report | |
* | |
* @return void | |
*/ | |
function _game_preprocess_report(&$report) { | |
// Format dates, can someone tell me how to do this directly in the | |
// query? | |
foreach ($report['table']['#rows'] as $key => $row) { | |
$time = $row['timestamp']; | |
$row['timestamp'] = date('Y-m-d H:i:s', $time); | |
$report['table']['#rows'][$key] = $row; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment