tablesort.inc

  1. drupal
    1. 4.6 includes/tablesort.inc
    2. 4.7 includes/tablesort.inc
    3. 5 includes/tablesort.inc
    4. 6 includes/tablesort.inc
    5. 7 includes/tablesort.inc
    6. 8 core/includes/tablesort.inc

Functions to aid in the creation of sortable tables.

All tables created with a call to theme('table') have the option of having column headers that the user can click on to sort the table by that column.

Classes

NameDescription
TableSortQuery extender class for tablesort queries.

Functions & methods

NameDescription
tablesort_cellFormat a table cell.
tablesort_get_orderDetermine the current sort criterion.
tablesort_get_query_parametersCompose a URL query parameter array for table sorting links.
tablesort_get_sortDetermine the current sort direction.
tablesort_headerFormat a column header.
tablesort_initInitialize the table sort context.

File

includes/tablesort.inc
View source
  1. <?php
  2. /**
  3. * @file
  4. * Functions to aid in the creation of sortable tables.
  5. *
  6. * All tables created with a call to theme('table') have the option of having
  7. * column headers that the user can click on to sort the table by that column.
  8. */
  9. /**
  10. * Query extender class for tablesort queries.
  11. */
  12. class TableSort extends SelectQueryExtender {
  13. /**
  14. * The array of fields that can be sorted by.
  15. *
  16. * @var array
  17. */
  18. protected $header = array();
  19. public function __construct(SelectQueryInterface $query, DatabaseConnection $connection) {
  20. parent::__construct($query, $connection);
  21. // Add convenience tag to mark that this is an extended query. We have to
  22. // do this in the constructor to ensure that it is set before preExecute()
  23. // gets called.
  24. $this->addTag('tablesort');
  25. }
  26. /**
  27. * Order the query based on a header array.
  28. *
  29. * @see theme_table()
  30. * @param $header
  31. * Table header array.
  32. * @return SelectQueryInterface
  33. * The called object.
  34. */
  35. public function orderByHeader(Array $header) {
  36. $this->header = $header;
  37. $ts = $this->init();
  38. if (!empty($ts['sql'])) {
  39. // Based on code from db_escape_table(), but this can also contain a dot.
  40. $field = preg_replace('/[^A-Za-z0-9_.]+/', '', $ts['sql']);
  41. // Sort order can only be ASC or DESC.
  42. $sort = drupal_strtoupper($ts['sort']);
  43. $sort = in_array($sort, array('ASC', 'DESC')) ? $sort : '';
  44. $this->orderBy($field, $sort);
  45. }
  46. return $this;
  47. }
  48. /**
  49. * Initialize the table sort context.
  50. */
  51. protected function init() {
  52. $ts = $this->order();
  53. $ts['sort'] = $this->getSort();
  54. $ts['query'] = $this->getQueryParameters();
  55. return $ts;
  56. }
  57. /**
  58. * Determine the current sort direction.
  59. *
  60. * @param $headers
  61. * An array of column headers in the format described in theme_table().
  62. * @return
  63. * The current sort direction ("asc" or "desc").
  64. */
  65. protected function getSort() {
  66. return tablesort_get_sort($this->header);
  67. }
  68. /**
  69. * Compose a URL query parameter array to append to table sorting requests.
  70. *
  71. * @return
  72. * A URL query parameter array that consists of all components of the current
  73. * page request except for those pertaining to table sorting.
  74. *
  75. * @see tablesort_get_query_parameters()
  76. */
  77. protected function getQueryParameters() {
  78. return tablesort_get_query_parameters();
  79. }
  80. /**
  81. * Determine the current sort criterion.
  82. *
  83. * @param $headers
  84. * An array of column headers in the format described in theme_table().
  85. * @return
  86. * An associative array describing the criterion, containing the keys:
  87. * - "name": The localized title of the table column.
  88. * - "sql": The name of the database field to sort on.
  89. */
  90. protected function order() {
  91. return tablesort_get_order($this->header);
  92. }
  93. }
  94. /**
  95. * Initialize the table sort context.
  96. */
  97. function tablesort_init($header) {
  98. $ts = tablesort_get_order($header);
  99. $ts['sort'] = tablesort_get_sort($header);
  100. $ts['query'] = tablesort_get_query_parameters();
  101. return $ts;
  102. }
  103. /**
  104. * Format a column header.
  105. *
  106. * If the cell in question is the column header for the current sort criterion,
  107. * it gets special formatting. All possible sort criteria become links.
  108. *
  109. * @param $cell
  110. * The cell to format.
  111. * @param $header
  112. * An array of column headers in the format described in theme_table().
  113. * @param $ts
  114. * The current table sort context as returned from tablesort_init().
  115. * @return
  116. * A properly formatted cell, ready for _theme_table_cell().
  117. */
  118. function tablesort_header($cell, $header, $ts) {
  119. // Special formatting for the currently sorted column header.
  120. if (is_array($cell) && isset($cell['field'])) {
  121. $title = t('sort by @s', array('@s' => $cell['data']));
  122. if ($cell['data'] == $ts['name']) {
  123. $ts['sort'] = (($ts['sort'] == 'asc') ? 'desc' : 'asc');
  124. $cell['class'][] = 'active';
  125. $image = theme('tablesort_indicator', array('style' => $ts['sort']));
  126. }
  127. else {
  128. // If the user clicks a different header, we want to sort ascending initially.
  129. $ts['sort'] = 'asc';
  130. $image = '';
  131. }
  132. $cell['data'] = l($cell['data'] . $image, $_GET['q'], array('attributes' => array('title' => $title), 'query' => array_merge($ts['query'], array('sort' => $ts['sort'], 'order' => $cell['data'])), 'html' => TRUE));
  133. unset($cell['field'], $cell['sort']);
  134. }
  135. return $cell;
  136. }
  137. /**
  138. * Format a table cell.
  139. *
  140. * Adds a class attribute to all cells in the currently active column.
  141. *
  142. * @param $cell
  143. * The cell to format.
  144. * @param $header
  145. * An array of column headers in the format described in theme_table().
  146. * @param $ts
  147. * The current table sort context as returned from tablesort_init().
  148. * @param $i
  149. * The index of the cell's table column.
  150. * @return
  151. * A properly formatted cell, ready for _theme_table_cell().
  152. */
  153. function tablesort_cell($cell, $header, $ts, $i) {
  154. if (isset($header[$i]['data']) && $header[$i]['data'] == $ts['name'] && !empty($header[$i]['field'])) {
  155. if (is_array($cell)) {
  156. $cell['class'][] = 'active';
  157. }
  158. else {
  159. $cell = array('data' => $cell, 'class' => array('active'));
  160. }
  161. }
  162. return $cell;
  163. }
  164. /**
  165. * Compose a URL query parameter array for table sorting links.
  166. *
  167. * @return
  168. * A URL query parameter array that consists of all components of the current
  169. * page request except for those pertaining to table sorting.
  170. */
  171. function tablesort_get_query_parameters() {
  172. return drupal_get_query_parameters($_GET, array('q', 'sort', 'order'));
  173. }
  174. /**
  175. * Determine the current sort criterion.
  176. *
  177. * @param $headers
  178. * An array of column headers in the format described in theme_table().
  179. * @return
  180. * An associative array describing the criterion, containing the keys:
  181. * - "name": The localized title of the table column.
  182. * - "sql": The name of the database field to sort on.
  183. */
  184. function tablesort_get_order($headers) {
  185. $order = isset($_GET['order']) ? $_GET['order'] : '';
  186. foreach ($headers as $header) {
  187. if (is_array($header)) {
  188. if (isset($header['data']) && $order == $header['data']) {
  189. $default = $header;
  190. break;
  191. }
  192. if (empty($default) && isset($header['sort']) && ($header['sort'] == 'asc' || $header['sort'] == 'desc')) {
  193. $default = $header;
  194. }
  195. }
  196. }
  197. if (!isset($default)) {
  198. $default = reset($headers);
  199. if (!is_array($default)) {
  200. $default = array('data' => $default);
  201. }
  202. }
  203. $default += array('data' => NULL, 'field' => NULL);
  204. return array('name' => $default['data'], 'sql' => $default['field']);
  205. }
  206. /**
  207. * Determine the current sort direction.
  208. *
  209. * @param $headers
  210. * An array of column headers in the format described in theme_table().
  211. * @return
  212. * The current sort direction ("asc" or "desc").
  213. */
  214. function tablesort_get_sort($headers) {
  215. if (isset($_GET['sort'])) {
  216. return (strtolower($_GET['sort']) == 'desc') ? 'desc' : 'asc';
  217. }
  218. // The user has not specified a sort. Use the default for the currently sorted
  219. // header if specified; otherwise use "asc".
  220. else {
  221. // Find out which header is currently being sorted.
  222. $ts = tablesort_get_order($headers);
  223. foreach ($headers as $header) {
  224. if (is_array($header) && isset($header['data']) && $header['data'] == $ts['name'] && isset($header['sort'])) {
  225. return $header['sort'];
  226. }
  227. }
  228. }
  229. return 'asc';
  230. }

Comments

Tablesort without a query

For some explanation and an example on how to use tablesort without a db query, see here here.

In summary, tablesort is triggered "automatically" if the (column) arrays in the $headers array contains the keys 'data', 'field' and optionally 'sort'. This will create links with 'sort' and 'order' in the column headers and show the little arrow and such.

To do your own sorting, get the current sort settings with tablesort_get_order and tablesort_get_sort and use those values for your own sorting function. The key 'sql' in the array returned by tablesort_get_order contains the field name to be used for sorting.

The VChess module uses manual

The VChess module uses manual sorting of each column to enable lists of games to be sorted:

<?php
/**
* Get table of current games for a given player
*/
function vchess_users_current_games($uid) {
  ... 
// initial, not relevant part of function not shown

 
$header = array(
      array(
'data' => t('Your move?'), 'field' => 'move'),
      array(
'data' => t('White'), 'field' => 'white'),
      array(
'data' => t('Black'), 'field' => 'black'),
     
t('View'));
 
 
// get the current sort and order parameters from the url
  // e.g. q=vchess/my_current_games&sort=asc&order=White
 
$order = tablesort_get_order($header); 
 
$sort = tablesort_get_sort($header);
 
 
// sort the table data accordingly (write your own sort function)
 
$rows = vchess_games_sort($rows, $order, $sort);
 
 
$table['header'] = $header;
 
$table['attributes'] = array();
 
$table['caption'] = array();
 
$table['colgroups'] = array();
 
$table['sticky'] = "";
 
$table['rows'] = $rows;
 
  return
theme_table($table);
}

/**
* Sort the games table
*/
function vchess_games_sort($rows, $order, $sort) {
  switch (
$order['sql']) {
    case
'move':
      if (
$sort == 'asc') {
       
usort($rows, "vchess_move_cmp_asc");
      }
      else {
       
usort($rows, "vchess_move_cmp_desc");
      }
      break;
    case
'white':
      if (
$sort == 'asc') {
       
usort($rows, "vchess_white_cmp_asc");
      }
      else {
       
usort($rows, "vchess_white_cmp_desc");
      }
      break;
    case
'black':
      if (
$sort == 'asc') {
       
usort($rows, "vchess_black_cmp_asc");
      }
      else {
       
usort($rows, "vchess_black_cmp_desc");
      }
      break;
  }

  return
$rows;
}

/**
* Compare function to enable 'move' games column to be sorted ascending
*/
function vchess_move_cmp_asc($a, $b) {
  return
strcmp($a['move'], $b['move']);
}

/**
* Compare function to enable 'move' games column to be sorted descending
*/
function vchess_move_cmp_desc($a, $b) {
  return
strcmp($b['move'], $a['move']);
}

/**
* Compare function to enable 'white' games column to be sorted ascending
*/
function vchess_white_cmp_asc($a, $b) {
  return
strcmp($a['white'], $b['white']);
}

/**
* Compare function to enable 'white' games column to be sorted descending
*/
function vchess_white_cmp_desc($a, $b) {
  return
strcmp($b['white'], $a['white']);
}

/**
* Compare function to enable 'black' games column to be sorted ascending
*/
function vchess_black_cmp_asc($a, $b) {
  return
strcmp($a['black'], $b['black']);
}

/**
* Compare function to enable 'black' games column to be sorted descending
*/
function vchess_black_cmp_desc($a, $b) {
  return
strcmp($b['black'], $a['black']);
}
?>

I can't help feeling there is a generic way to do this though!

Login or register to post comments