From 3c92b1d4e55196cb5de306bb30dee07d0a54f293 Mon Sep 17 00:00:00 2001 From: Paul Holden Date: Thu, 4 Apr 2019 16:08:26 +0100 Subject: [PATCH] MDL-64784 core: consistent column sort direction in flexible_table. --- lib/tablelib.php | 25 ++++++++++++++++++++----- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/lib/tablelib.php b/lib/tablelib.php index d1213b89b47..421632cbc0c 100644 --- a/lib/tablelib.php +++ b/lib/tablelib.php @@ -35,6 +35,7 @@ define('TABLE_VAR_IFIRST', 4); define('TABLE_VAR_ILAST', 5); define('TABLE_VAR_PAGE', 6); define('TABLE_VAR_RESET', 7); +define('TABLE_VAR_DIR', 8); /**#@-*/ /**#@+ @@ -150,7 +151,8 @@ class flexible_table { TABLE_VAR_IFIRST => 'tifirst', TABLE_VAR_ILAST => 'tilast', TABLE_VAR_PAGE => 'page', - TABLE_VAR_RESET => 'treset' + TABLE_VAR_RESET => 'treset', + TABLE_VAR_DIR => 'tdir', ); } @@ -516,14 +518,16 @@ class flexible_table { (isset($this->columns[$sortcol]) || in_array($sortcol, get_all_user_name_fields()) && isset($this->columns['fullname']))) { + $sortdir = optional_param($this->request[TABLE_VAR_DIR], $this->sort_default_order, PARAM_INT); + if (array_key_exists($sortcol, $this->prefs['sortby'])) { // This key already exists somewhere. Change its sortorder and bring it to the top. - $sortorder = $this->prefs['sortby'][$sortcol] == SORT_ASC ? SORT_DESC : SORT_ASC; + $sortorder = $this->prefs['sortby'][$sortcol] = $sortdir; unset($this->prefs['sortby'][$sortcol]); $this->prefs['sortby'] = array_merge(array($sortcol => $sortorder), $this->prefs['sortby']); } else { // Key doesn't exist, so just add it to the beginning of the array, ascending order - $this->prefs['sortby'] = array_merge(array($sortcol => SORT_ASC), $this->prefs['sortby']); + $this->prefs['sortby'] = array_merge(array($sortcol => $sortdir), $this->prefs['sortby']); } // Finally, make sure that no more than $this->maxsortkeys are present into the array @@ -1362,8 +1366,19 @@ class flexible_table { * @return string HTML fragment. */ protected function sort_link($text, $column, $isprimary, $order) { - return html_writer::link($this->baseurl->out(false, - array($this->request[TABLE_VAR_SORT] => $column)), + // If we are already sorting by this column, switch direction. + if (array_key_exists($column, $this->prefs['sortby'])) { + $sortorder = $this->prefs['sortby'][$column] == SORT_ASC ? SORT_DESC : SORT_ASC; + } else { + $sortorder = $order; + } + + $params = [ + $this->request[TABLE_VAR_SORT] => $column, + $this->request[TABLE_VAR_DIR] => $sortorder, + ]; + + return html_writer::link($this->baseurl->out(false, $params), $text . get_accesshide(get_string('sortby') . ' ' . $text . ' ' . $this->sort_order_name($isprimary, $order))) . ' ' . $this->sort_icon($isprimary, $order);