tablesort_example.module 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. /**
  3. * @file
  4. * This is an example describing how a module can display data in a sortable
  5. * table
  6. *
  7. * See:
  8. * @link http://drupal.org/node/508796 Extenders @endlink
  9. * @link http://drupal.org/developing/api/database Database API @endlink
  10. */
  11. /**
  12. * @defgroup tablesort_example Example: Tablesort
  13. * @ingroup examples
  14. * @{
  15. * Example of a sortable table display.
  16. */
  17. /**
  18. * Implements hook_help().
  19. *
  20. * Show a bit of information about this module on the example page
  21. */
  22. function tablesort_example_help($path, $arg) {
  23. switch ($path) {
  24. case 'examples/tablesort_example':
  25. return '<p>' . t('The layout here is a themed as a table that is sortable by clicking the header name.') . '</p>';
  26. }
  27. }
  28. /**
  29. * Implements hook_menu().
  30. */
  31. function tablesort_example_menu() {
  32. $items['examples/tablesort_example'] = array(
  33. 'title' => 'TableSort example',
  34. 'description' => 'Show a page with a sortable table',
  35. 'page callback' => 'tablesort_example_page',
  36. 'access callback' => TRUE,
  37. );
  38. return $items;
  39. }
  40. /**
  41. * Build the table render array.
  42. *
  43. * @return array
  44. * A render array set for theming by theme_table().
  45. */
  46. function tablesort_example_page() {
  47. // We are going to output the results in a table with a nice header.
  48. $header = array(
  49. // The header gives the table the information it needs in order to make
  50. // the query calls for ordering. TableSort uses the field information
  51. // to know what database column to sort by.
  52. array('data' => t('Numbers'), 'field' => 't.numbers'),
  53. array('data' => t('Letters'), 'field' => 't.alpha'),
  54. array('data' => t('Mixture'), 'field' => 't.random'),
  55. );
  56. // Using the TableSort Extender is what tells the query object that we are
  57. // sorting.
  58. $query = db_select('tablesort_example', 't')
  59. ->extend('TableSort');
  60. $query->fields('t');
  61. // Don't forget to tell the query object how to find the header information.
  62. $result = $query
  63. ->orderByHeader($header)
  64. ->execute();
  65. $rows = array();
  66. foreach ($result as $row) {
  67. // Normally we would add some nice formatting to our rows
  68. // but for our purpose we are simply going to add our row
  69. // to the array.
  70. $rows[] = array('data' => (array) $row);
  71. }
  72. // Build the table for the nice output.
  73. $build['tablesort_table'] = array(
  74. '#theme' => 'table',
  75. '#header' => $header,
  76. '#rows' => $rows,
  77. );
  78. return $build;
  79. }
  80. /**
  81. * @} End of "defgroup tablesort_example".
  82. */