phpsortinggridviewyii2

Sorting Yii2 Gridview in descending order first


I have a table rendered by Yii2 GridView. The table header contains the link to sort by date. If I click on it, it sorts the table first in ascending order and on the second click in descending order. But I want descending order on the first click.

I solved it with a hack in the search method of the search controller (asc->SORT_DESC):

   $dataProvider->sort->attributes['updated_at'] = [ 
      'asc'  => [$this->tablename() . '.updated_at' => SORT_DESC ], 
      'desc' => [$this->tablename() . '.updated_at' => SORT_ASC], 
   ]; 

Is there a better solution?


Solution

  • Use default:

    The "default" element specifies by which direction the attribute should be sorted if it is not currently sorted (the default value is ascending order).

    $dataProvider->sort->attributes['updated_at'] = [ 
        'default' => SORT_DESC
    ];