27

How to enable and disable sort in Yii2 GridView ?

Example

rdanusha
  • 856
  • 3
  • 14
  • 23

4 Answers4

49

You can customize columns sort in your DataProvider. For example if you use ActiveDataProvider in your GridView you can indicate sort-able columns like below:

$dataProvider = new ActiveDataProvider([
    'query' => Model::find(),
    'sort' => ['attributes' => ['column1','column2']]
]);

In above example, only column1 and column2 are sort-able.

You can also disable sorting for all columns like below:

'sort' =>false

It is suggested to take a look at Yii2's official document : Class yii\data\Sort As it defines it:

Sort represents information relevant to sorting. When data needs to be sorted according to one or several attributes, we can use Sort to represent the sorting information and generate appropriate hyperlinks that can lead to sort actions.

Ali MasudianPour
  • 13,704
  • 3
  • 57
  • 61
18

In addition to Ali's answer, for aggregated and related columns you could do the following:

public function actionIndex()
{
    $dataProvider = new ActiveDataProvider([
          'query' => User::find()->joinWith('role'),
          'sort' => ['attributes' => [
                   //Normal columns
                   'username',
                   'email',
                   //aggregated columns
                   'full_name' => [
                        'asc' => ['first_name' => SORT_ASC, 'last_name' => SORT_ASC],
                        'desc' => ['first_name' => SORT_DESC, 'last_name' => SORT_DESC],
                        'default' => SORT_DESC
                   ],
                   //related columns
                   'role.name' => [
                        'asc' => ['user_role.name' => SORT_ASC],
                        'desc' => ['user_role.name' => SORT_DESC],
                        'default' => SORT_DESC
                   ],
              ],],
    ]);
}

Source: http://www.yiiframework.com/doc-2.0/yii-data-sort.html

Ehsan Khaveh
  • 1,163
  • 12
  • 19
11

If you want disable sorting from gridview for particular column then do like this:

 [
     'attribute' => 'name',
     'enableSorting' => false
 ],

by using 'enableSorting' => false

Rohit Suthar
  • 3,303
  • 1
  • 34
  • 46
Priyanka
  • 291
  • 1
  • 6
  • 8
  • This also works when you wish to apply a sort to an ActiveDataProvider but then not allow the user to re-sort. Thanks :) – Rich Harding Sep 28 '18 at 12:17
6

You can disable sort in controller like this:

$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$dataProvider->sort->sortParam = false;
pa3py6aka
  • 529
  • 7
  • 9