tablesort.inc 4.77 KB
Newer Older
1 2
<?php

3 4 5 6
/**
 * @file
 * Functions to aid in the creation of sortable tables.
 *
7
 * All tables created when rendering a '#type' => 'table' have the option of
8 9
 * having column headers that the user can click on to sort the table by that
 * column.
10 11
 */

12
use Drupal\Component\Render\FormattableMarkup;
13 14 15
use Drupal\Core\Url;
use Drupal\Component\Utility\UrlHelper;

16
/**
17
 * Initializes the table sort context.
18
 */
Dries's avatar
Dries committed
19 20 21
function tablesort_init($header) {
  $ts = tablesort_get_order($header);
  $ts['sort'] = tablesort_get_sort($header);
22
  $ts['query'] = tablesort_get_query_parameters();
23 24 25
  return $ts;
}

26
/**
27
 * Formats a column header.
28 29 30 31
 *
 * If the cell in question is the column header for the current sort criterion,
 * it gets special formatting. All possible sort criteria become links.
 *
32 33 34 35 36
 * @param string $cell_content
 *   The cell content to format. Passed by reference.
 * @param array $cell_attributes
 *   The cell attributes. Passed by reference.
 * @param array $header
37
 *   An array of column headers in the format described in '#type' => 'table'.
38
 * @param array $ts
39 40
 *   The current table sort context as returned from tablesort_init().
 */
41
function tablesort_header(&$cell_content, array &$cell_attributes, array $header, array $ts) {
42
  // Special formatting for the currently sorted column header.
43
  if (isset($cell_attributes['field'])) {
44
    $title = t('sort by @s', ['@s' => $cell_content]);
45
    if ($cell_content == $ts['name']) {
46 47 48
      // aria-sort is a WAI-ARIA property that indicates if items in a table
      // or grid are sorted in ascending or descending order. See
      // http://www.w3.org/TR/wai-aria/states_and_properties#aria-sort
49
      $cell_attributes['aria-sort'] = ($ts['sort'] == 'asc') ? 'ascending' : 'descending';
50
      $ts['sort'] = (($ts['sort'] == 'asc') ? 'desc' : 'asc');
51
      $cell_attributes['class'][] = 'is-active';
52
      $tablesort_indicator = [
53 54
        '#theme' => 'tablesort_indicator',
        '#style' => $ts['sort'],
55
      ];
56
      $image = \Drupal::service('renderer')->render($tablesort_indicator);
57 58
    }
    else {
59
      // If the user clicks a different header, we want to sort ascending initially.
60
      $ts['sort'] = 'asc';
61
      $image = '';
62
    }
63
    $cell_content = \Drupal::l(new FormattableMarkup('@cell_content@image', ['@cell_content' => $cell_content, '@image' => $image]), new Url('<current>', [], [
64 65
      'attributes' => ['title' => $title],
      'query' => array_merge($ts['query'], [
66 67
        'sort' => $ts['sort'],
        'order' => $cell_content,
68
      ]),
69
    ]));
70

71
    unset($cell_attributes['field'], $cell_attributes['sort']);
72
  }
73 74
}

75
/**
76
 * Composes a URL query parameter array for table sorting links.
77 78
 *
 * @return
79 80
 *   A URL query parameter array that consists of all components of the current
 *   page request except for those pertaining to table sorting.
81
 */
82
function tablesort_get_query_parameters() {
83
  return UrlHelper::filterQueryParameters(\Drupal::request()->query->all(), ['sort', 'order']);
84 85
}

86
/**
87
 * Determines the current sort criterion.
88 89
 *
 * @param $headers
90
 *   An array of column headers in the format described in '#type' => 'table'.
91
 *
92 93 94 95 96
 * @return
 *   An associative array describing the criterion, containing the keys:
 *   - "name": The localized title of the table column.
 *   - "sql": The name of the database field to sort on.
 */
Dries's avatar
Dries committed
97
function tablesort_get_order($headers) {
98
  $order = \Drupal::request()->query->get('order', '');
99
  foreach ($headers as $header) {
100 101 102 103 104
    if (is_array($header)) {
      if (isset($header['data']) && $order == $header['data']) {
        $default = $header;
        break;
      }
105

106 107 108
      if (empty($default) && isset($header['sort']) && ($header['sort'] == 'asc' || $header['sort'] == 'desc')) {
        $default = $header;
      }
109 110 111
    }
  }

112 113 114
  if (!isset($default)) {
    $default = reset($headers);
    if (!is_array($default)) {
115
      $default = ['data' => $default];
116 117
    }
  }
118

119 120
  $default += ['data' => NULL, 'field' => NULL];
  return ['name' => $default['data'], 'sql' => $default['field']];
121 122
}

123
/**
124
 * Determines the current sort direction.
125 126
 *
 * @param $headers
127
 *   An array of column headers in the format described in '#type' => 'table'.
128
 *
129 130 131
 * @return
 *   The current sort direction ("asc" or "desc").
 */
Dries's avatar
Dries committed
132
function tablesort_get_sort($headers) {
133
  $query = \Drupal::request()->query;
134 135
  if ($query->has('sort')) {
    return (strtolower($query->get('sort')) == 'desc') ? 'desc' : 'asc';
136
  }
137 138
  // The user has not specified a sort. Use the default for the currently sorted
  // header if specified; otherwise use "asc".
139
  else {
140 141
    // Find out which header is currently being sorted.
    $ts = tablesort_get_order($headers);
142
    foreach ($headers as $header) {
143
      if (is_array($header) && isset($header['data']) && $header['data'] == $ts['name'] && isset($header['sort'])) {
144
        return $header['sort'];
145 146 147 148 149
      }
    }
  }
  return 'asc';
}