From 898dd7bf5bfc733f444bd10a58024fbf705945a8 Mon Sep 17 00:00:00 2001 From: Paul Holden Date: Wed, 21 Oct 2020 00:22:23 +0100 Subject: [PATCH] MDL-69201 core: consistent table primary sort column/order. --- lib/tablelib.php | 30 ++++++++++++++++++++++-------- 1 file changed, 22 insertions(+), 8 deletions(-) diff --git a/lib/tablelib.php b/lib/tablelib.php index 63510a655196d..e464d39e8be46 100644 --- a/lib/tablelib.php +++ b/lib/tablelib.php @@ -1201,6 +1201,12 @@ protected function show_hide_link($column, $index) { function print_headers() { global $CFG, $OUTPUT; + // Set the primary sort column/order where possible, so that sort links/icons are correct. + [ + 'sortby' => $primarysortcolumn, + 'sortorder' => $primarysortorder, + ] = $this->get_primary_sort_order(); + echo html_writer::start_tag('thead'); echo html_writer::start_tag('tr'); foreach ($this->columns as $column => $index) { @@ -1209,14 +1215,6 @@ function print_headers() { if ($this->is_collapsible) { $icon_hide = $this->show_hide_link($column, $index); } - - $primarysortcolumn = ''; - $primarysortorder = ''; - if (reset($this->prefs['sortby'])) { - $primarysortcolumn = key($this->prefs['sortby']); - $primarysortorder = current($this->prefs['sortby']); - } - switch ($column) { case 'fullname': @@ -1596,6 +1594,22 @@ protected function sort_link($text, $column, $isprimary, $order) { ]) . ' ' . $this->sort_icon($isprimary, $order); } + /** + * Return primary sorting column/order, either the first preferred "sortby" value or defaults defined for the table + * + * @return array + */ + protected function get_primary_sort_order(): array { + if (reset($this->prefs['sortby'])) { + return $this->get_sort_order(); + } + + return [ + 'sortby' => $this->sort_default_column, + 'sortorder' => $this->sort_default_order, + ]; + } + /** * Return sorting attributes values. *