pager.inc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. <?php
  2. /**
  3. * @file
  4. * Functions to aid in presenting database results as a set of pages.
  5. */
  6. use Drupal\Component\Utility\UrlHelper;
  7. /**
  8. * Returns the current page being requested for display within a pager.
  9. *
  10. * @param int $element
  11. * (optional) An integer to distinguish between multiple pagers on one page.
  12. *
  13. * @return int
  14. * The number of the current requested page, within the pager represented by
  15. * $element. This is determined from the URL query parameter
  16. * \Drupal::request()->query->get('page'), or 0 by default. Note that this
  17. * number may differ from the actual page being displayed. For example, if a
  18. * search for "example text" brings up three pages of results, but a user
  19. * visits search/node/example+text?page=10, this function will return 10,
  20. * even though the default pager implementation adjusts for this and still
  21. * displays the third page of search results at that URL.
  22. *
  23. * @see pager_default_initialize()
  24. */
  25. function pager_find_page($element = 0) {
  26. $page = \Drupal::request()->query->get('page', '');
  27. $page_array = explode(',', $page);
  28. if (!isset($page_array[$element])) {
  29. $page_array[$element] = 0;
  30. }
  31. return (int) $page_array[$element];
  32. }
  33. /**
  34. * Initializes a pager.
  35. *
  36. * This function sets up the necessary global variables so that the render
  37. * system will correctly process #type 'pager' render arrays to output pagers
  38. * that correspond to the items being displayed.
  39. *
  40. * If the items being displayed result from a database query performed using
  41. * Drupal's database API, and if you have control over the construction of the
  42. * database query, you do not need to call this function directly; instead, you
  43. * can simply extend the query object with the 'PagerSelectExtender' extender
  44. * before executing it. For example:
  45. * @code
  46. * $query = db_select('some_table')
  47. * ->extend('Drupal\Core\Database\Query\PagerSelectExtender');
  48. * @endcode
  49. *
  50. * However, if you are using a different method for generating the items to be
  51. * paged through, then you should call this function in preparation.
  52. *
  53. * The following example shows how this function can be used in a controller
  54. * that invokes an external datastore with an SQL-like syntax:
  55. * @code
  56. * // First find the total number of items and initialize the pager.
  57. * $where = "status = 1";
  58. * $total = mymodule_select("SELECT COUNT(*) FROM data " . $where)->result();
  59. * $num_per_page = \Drupal::config('mymodule.settings')->get('num_per_page');
  60. * $page = pager_default_initialize($total, $num_per_page);
  61. *
  62. * // Next, retrieve the items for the current page and put them into a
  63. * // render array.
  64. * $offset = $num_per_page * $page;
  65. * $result = mymodule_select("SELECT * FROM data " . $where . " LIMIT %d, %d", $offset, $num_per_page)->fetchAll();
  66. * $render = [];
  67. * $render[] = [
  68. * '#theme' => 'mymodule_results',
  69. * '#result' => $result,
  70. * ];
  71. *
  72. * // Finally, add the pager to the render array, and return.
  73. * $render[] = ['#type' => 'pager'];
  74. * return $render;
  75. * @endcode
  76. *
  77. * A second example involves a controller that invokes an external search
  78. * service where the total number of matching results is provided as part of
  79. * the returned set (so that we do not need a separate query in order to obtain
  80. * this information). Here, we call pager_find_page() to calculate the desired
  81. * offset before the search is invoked:
  82. * @code
  83. * // Perform the query, using the requested offset from pager_find_page().
  84. * // This comes from a URL parameter, so here we are assuming that the URL
  85. * // parameter corresponds to an actual page of results that will exist
  86. * // within the set.
  87. * $page = pager_find_page();
  88. * $num_per_page = \Drupal::config('mymodule.settings')->get('num_per_page');
  89. * $offset = $num_per_page * $page;
  90. * $result = mymodule_remote_search($keywords, $offset, $num_per_page);
  91. *
  92. * // Now that we have the total number of results, initialize the pager.
  93. * pager_default_initialize($result->total, $num_per_page);
  94. *
  95. * // Create a render array with the search results.
  96. * $render = [];
  97. * $render[] = [
  98. * '#theme' => 'search_results',
  99. * '#results' => $result->data,
  100. * '#type' => 'remote',
  101. * ];
  102. *
  103. * // Finally, add the pager to the render array, and return.
  104. * $render[] = ['#type' => 'pager'];
  105. * return $render;
  106. * @endcode
  107. *
  108. * @param int $total
  109. * The total number of items to be paged.
  110. * @param int $limit
  111. * The number of items the calling code will display per page.
  112. * @param int $element
  113. * (optional) An integer to distinguish between multiple pagers on one page.
  114. *
  115. * @return int
  116. * The number of the current page, within the pager represented by $element.
  117. * This is determined from the URL query parameter
  118. * \Drupal::request()->query->get('page), or 0 by default. However, if a page
  119. * that does not correspond to the actual range of the result set was
  120. * requested, this function will return the closest page actually within the
  121. * result set.
  122. */
  123. function pager_default_initialize($total, $limit, $element = 0) {
  124. global $pager_page_array, $pager_total, $pager_total_items, $pager_limits;
  125. $page = pager_find_page($element);
  126. // We calculate the total of pages as ceil(items / limit).
  127. $pager_total_items[$element] = $total;
  128. $pager_total[$element] = ceil($pager_total_items[$element] / $limit);
  129. $pager_page_array[$element] = max(0, min($page, ((int) $pager_total[$element]) - 1));
  130. $pager_limits[$element] = $limit;
  131. return $pager_page_array[$element];
  132. }
  133. /**
  134. * Compose a URL query parameter array for pager links.
  135. *
  136. * @return array
  137. * A URL query parameter array that consists of all components of the current
  138. * page request except for those pertaining to paging.
  139. */
  140. function pager_get_query_parameters() {
  141. $query = &drupal_static(__FUNCTION__);
  142. if (!isset($query)) {
  143. $query = UrlHelper::filterQueryParameters(\Drupal::request()->query->all(), array('page'));
  144. }
  145. return $query;
  146. }
  147. /**
  148. * Prepares variables for pager templates.
  149. *
  150. * Default template: pager.html.twig.
  151. *
  152. * Menu callbacks that display paged query results should use #type => pager
  153. * to retrieve a pager control so that users can view other results. Format a
  154. * list of nearby pages with additional query results.
  155. *
  156. * @param array $variables
  157. * An associative array containing:
  158. * - pager: A render element containing:
  159. * - #tags: An array of labels for the controls in the pager.
  160. * - #element: An optional integer to distinguish between multiple pagers on
  161. * one page.
  162. * - #parameters: An associative array of query string parameters to append
  163. * to the pager links.
  164. * - #route_parameters: An associative array of the route parameters.
  165. * - #quantity: The number of pages in the list.
  166. */
  167. function template_preprocess_pager(&$variables) {
  168. $element = $variables['pager']['#element'];
  169. $parameters = $variables['pager']['#parameters'];
  170. $quantity = $variables['pager']['#quantity'];
  171. $route_name = $variables['pager']['#route_name'];
  172. $route_parameters = isset($variables['pager']['#route_parameters']) ? $variables['pager']['#route_parameters'] : [];
  173. global $pager_page_array, $pager_total;
  174. // Nothing to do if there is only one page.
  175. if ($pager_total[$element] <= 1) {
  176. return;
  177. }
  178. $tags = $variables['pager']['#tags'];
  179. // Calculate various markers within this pager piece:
  180. // Middle is used to "center" pages around the current page.
  181. $pager_middle = ceil($quantity / 2);
  182. // current is the page we are currently paged to.
  183. $pager_current = $pager_page_array[$element] + 1;
  184. // first is the first page listed by this pager piece (re quantity).
  185. $pager_first = $pager_current - $pager_middle + 1;
  186. // last is the last page listed by this pager piece (re quantity).
  187. $pager_last = $pager_current + $quantity - $pager_middle;
  188. // max is the maximum page number.
  189. $pager_max = $pager_total[$element];
  190. // End of marker calculations.
  191. // Prepare for generation loop.
  192. $i = $pager_first;
  193. if ($pager_last > $pager_max) {
  194. // Adjust "center" if at end of query.
  195. $i = $i + ($pager_max - $pager_last);
  196. $pager_last = $pager_max;
  197. }
  198. if ($i <= 0) {
  199. // Adjust "center" if at start of query.
  200. $pager_last = $pager_last + (1 - $i);
  201. $i = 1;
  202. }
  203. // End of generation loop preparation.
  204. // Create the "first" and "previous" links if we are not on the first page.
  205. if ($pager_page_array[$element] > 0) {
  206. $items['first'] = array();
  207. $options = array(
  208. 'query' => pager_query_add_page($parameters, $element, 0),
  209. );
  210. $items['first']['href'] = \Drupal::url($route_name, $route_parameters, $options);
  211. if (isset($tags[0])) {
  212. $items['first']['text'] = $tags[0];
  213. }
  214. $items['previous'] = array();
  215. $options = array(
  216. 'query' => pager_query_add_page($parameters, $element, $pager_page_array[$element] - 1),
  217. );
  218. $items['previous']['href'] = \Drupal::url($route_name, $route_parameters, $options);
  219. if (isset($tags[1])) {
  220. $items['previous']['text'] = $tags[1];
  221. }
  222. }
  223. if ($i != $pager_max) {
  224. // Add an ellipsis if there are further previous pages.
  225. if ($i > 1) {
  226. $variables['ellipses']['previous'] = TRUE;
  227. }
  228. // Now generate the actual pager piece.
  229. for (; $i <= $pager_last && $i <= $pager_max; $i++) {
  230. $options = array(
  231. 'query' => pager_query_add_page($parameters, $element, $i - 1),
  232. );
  233. $items['pages'][$i]['href'] = \Drupal::url($route_name, $route_parameters, $options);
  234. if ($i == $pager_current) {
  235. $variables['current'] = $i;
  236. }
  237. }
  238. // Add an ellipsis if there are further next pages.
  239. if ($i < $pager_max + 1) {
  240. $variables['ellipses']['next'] = TRUE;
  241. }
  242. }
  243. // Create the "next" and "last" links if we are not on the last page.
  244. if ($pager_page_array[$element] < ($pager_max - 1)) {
  245. $items['next'] = array();
  246. $options = array(
  247. 'query' => pager_query_add_page($parameters, $element, $pager_page_array[$element] + 1),
  248. );
  249. $items['next']['href'] = \Drupal::url($route_name, $route_parameters, $options);
  250. if (isset($tags[3])) {
  251. $items['next']['text'] = $tags[3];
  252. }
  253. $items['last'] = array();
  254. $options = array(
  255. 'query' => pager_query_add_page($parameters, $element, $pager_max - 1),
  256. );
  257. $items['last']['href'] = \Drupal::url($route_name, $route_parameters, $options);
  258. if (isset($tags[4])) {
  259. $items['last']['text'] = $tags[4];
  260. }
  261. }
  262. $variables['items'] = $items;
  263. // The rendered link needs to play well with any other query parameter used
  264. // on the page, like exposed filters, so for the cacheability all query
  265. // parameters matter.
  266. $variables['#cache']['contexts'][] = 'url.query_args';
  267. }
  268. /**
  269. * Gets the URL query parameter array of a pager link.
  270. *
  271. * Adds to or adjusts the 'page' URL query parameter so that if you follow the
  272. * link, you'll get page $index for pager $element on the page.
  273. *
  274. * The 'page' URL query parameter is a comma-delimited string, where each value
  275. * is the target content page for the corresponding pager $element. For
  276. * instance, if we have 5 pagers on a single page, and we want to have a link
  277. * to a page that should display the 6th content page for the 3rd pager, and
  278. * the 1st content page for all the other pagers, then the URL query will look
  279. * like this: ?page=0,0,5,0,0 (page numbering starts at zero).
  280. *
  281. * @param array $query
  282. * An associative array of URL query parameters to add to.
  283. * @param int $element
  284. * An integer to distinguish between multiple pagers on one page.
  285. * @param int $index
  286. * The index of the target page, for the given element, in the pager array.
  287. *
  288. * @return array
  289. * The altered $query parameter array.
  290. */
  291. function pager_query_add_page(array $query, $element, $index) {
  292. global $pager_page_array;
  293. // Build the 'page' query parameter. This is built based on the current
  294. // page of each pager element (or NULL if the pager is not set), with the
  295. // exception of the requested page index for the current element.
  296. $max_element = max(array_keys($pager_page_array));
  297. $element_pages = [];
  298. for ($i = 0; $i <= $max_element; $i++) {
  299. $element_pages[] = ($i == $element) ? $index : (isset($pager_page_array[$i]) ? $pager_page_array[$i] : NULL);
  300. }
  301. $query['page'] = implode(',', $element_pages);
  302. // Merge the query parameters passed to this function with the parameters
  303. // from the current request. In case of collision, the parameters passed into
  304. // this function take precedence.
  305. if ($current_request_query = pager_get_query_parameters()) {
  306. $query = array_merge($current_request_query, $query);
  307. }
  308. return $query;
  309. }