I'm using Yii 2
and I have created a Pagination and Sort system and have the following code:
Here is the generalized code:
$sql = $this->db->createCommand("SELECT COUNT(*) FROM some_table WHERE some_id=:some_id");
$sql->bindValue(':some_id', $this->some_id);
$count = $sql->queryScalar();
$dataProvider = new SqlDataProvider([
'sql' => 'SELECT * FROM some_table WHERE some_id=:some_id',
'params' => [':some_id' => $this->some_id],
'totalCount' => $count,
'sort' => [
'attributes' => [
'sort_way_1' => [
'asc' => ['col_1' => SORT_DESC, 'col_2' => SORT_ASC, 'col_3' => SORT_ASC],
'desc' => ['col_1' => SORT_DESC, 'col_2' => SORT_DESC, 'col_3' => SORT_DESC],
'default' => SORT_DESC,
'label' => 'Sort Way 1',
],
'sort_way_2' => [
'asc' => ['col_1' => SORT_DESC, 'col_4' => SORT_ASC, 'col_3' => SORT_ASC],
'desc' => ['col_1' => SORT_DESC, 'col_4' => SORT_DESC, 'col_3' => SORT_DESC],
'default' => SORT_DESC,
'label' => 'Sort Way 2',
],
'sort_way_3' => [
'asc' => ['col_1' => SORT_DESC, 'col_5' => SORT_ASC, 'col_3' => SORT_ASC],
'desc' => ['col_1' => SORT_DESC, 'col_5' => SORT_DESC, 'col_3' => SORT_DESC],
'default' => SORT_DESC,
'label' => 'Sort Way 3',
],
'sort_way_4' => [
'asc' => ['col_1' => SORT_DESC, 'col_6' => SORT_ASC, 'col_3' => SORT_ASC],
'desc' => ['col_1' => SORT_DESC, 'col_6' => SORT_DESC, 'col_3' => SORT_DESC],
'default' => SORT_DESC,
'label' => 'Sort Way 4',
],
],
'enableMultiSort' => false,
'defaultOrder' => ['sort_way_1' => SORT_DESC],
],
'pagination' => [
'defaultPageSize' => $this->per_page,
'pageSize' => $this->per_page,
'pageSizeLimit' => [5,100],
'pageSizeParam' => 'per_page',
'totalCount' => $count,
],
]);
Now for my sorting links I attempted to create the URL's with the createUrl method and everything works fine, except for the fact it appends a -
to the start of the sort attribute name in the URL (apart from the first sort method).
Example:
http://example.com/some_dir/?page=1&sort=sort_way_1 (good)
http://example.com/some_dir/?page=1&sort=-sort_way_2 (bad)
I then tried doing it with the LinkSorter Widget but I got the same results.
I dug into the code a bit and found the below code inside the sort.php
createSortParam method:
foreach ($directions as $attribute => $direction) {
$sorts[] = $direction === SORT_DESC ? '-' . $attribute : $attribute;
}
This appears to be the culprit for the appended hyphen, but I'm not sure why it does it or why it doesn't add it to the first sorting attribute.
Does anyone have any more info on this or how to get around it? As with the appended hyphens the requested sorting method is coming back as invalid.