How to enable and disable sort in Yii2 GridView ?
4 Answers
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.
- 13,704
- 3
- 57
- 61
-
This did it for me, amazing. Thank you! – Paramone Apr 30 '15 at 15:01
-
How can I sort relational and aggregation data? – Ejaz Karim May 17 '15 at 15:51
-
I've not found a way of making this work in a scenario where you wish to apply a sort to an ActiveDataProvider but then not allow the user to re-sort. For such a scenario, you can apply @Priyanka's solution. – Rich Harding Sep 28 '18 at 12:16
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
- 1,163
- 12
- 19
-
1Hello! Could you please tell me how do sorting for double relation? E.g `location.city.name` – Sergey Mishin Mar 01 '19 at 10:37
If you want disable sorting from gridview for particular column then do like this:
[
'attribute' => 'name',
'enableSorting' => false
],
by using 'enableSorting' => false
- 3,303
- 1
- 34
- 46
- 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
You can disable sort in controller like this:
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$dataProvider->sort->sortParam = false;
- 529
- 7
- 9