Yii2 data provider default sorting

PhpYiiYii2Gridview Sorting

Php Problem Overview


In Yii 1.1 this code works for default sorting:

$dataProvider = new CActiveDataProvider('article',array(
    'sort'=>array(
        'defaultOrder'=>'id DESC',
    ),
));

How default sorting can be set in Yii2?

Tried below code, but no result:

$dataProvider = new ActiveDataProvider([
	'query' => $query,
	'sort' => ['defaultOrder'=>'topic_order asc']
]);

Php Solutions


Solution 1 - Php

I think there's proper solution. Configure the yii\data\Sort object:

 $dataProvider = new ActiveDataProvider([
     'query' => $query,
     'sort'=> ['defaultOrder' => ['topic_order' => SORT_ASC]],
 ]);

Official doc link

Solution 2 - Php

Or

       $dataProvider->setSort([
        'defaultOrder' => ['topic_order'=>SORT_DESC],
        'attributes' => [...

Solution 3 - Php

defaultOrder contain a array where key is a column name and value is a SORT_DESC or SORT_ASC that's why below code not working.

$dataProvider = new ActiveDataProvider([
        'query' => $query,
        'sort' => ['defaultOrder'=>'topic_order asc']
    ]);

Correct Way

$dataProvider = new ActiveDataProvider([
    'query' => $query,
    'sort' => [
        'defaultOrder' => [
            'topic_order' => SORT_ASC,
        ]
    ],
]);

Note: If a query already specifies the orderBy clause, the new ordering instructions given by end users (through the sort configuration) will be appended to the existing orderBy clause. Any existing limit and offset clauses will be overwritten by the pagination request from end users (through the pagination configuration).

You can detail learn from Yii2 Guide of Data Provider

Sorting By passing Sort object in query

 $sort = new Sort([
        'attributes' => [
            'age',
            'name' => [
                'asc' => ['first_name' => SORT_ASC, 'last_name' => SORT_ASC],
                'desc' => ['first_name' => SORT_DESC, 'last_name' => SORT_DESC],
                'default' => SORT_DESC,
                'label' => 'Name',
            ],
        ],
    ]);

    $models = Article::find()
        ->where(['status' => 1])
        ->orderBy($sort->orders)
        ->all();

Solution 4 - Php

if you have CRUD (index) and you need set default sorting your controller for GridView, or ListView, or more... Example

public function actionIndex()
{
    $searchModel = new NewsSearch();
    $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
    // set default sorting
    $dataProvider->sort->defaultOrder = ['id' => SORT_DESC];

    return $this->render('index', [
        'searchModel' => $searchModel,
        'dataProvider' => $dataProvider,
    ]);
}

you need add

$dataProvider->sort->defaultOrder = ['id' => SORT_DESC];

Solution 5 - Php

Try to this one

$dataProvider = new ActiveDataProvider([
    'query' => $query,
]);

$sort = $dataProvider->getSort();

$sort->defaultOrder = ['id' => SORT_ASC];

$dataProvider->setSort($sort);

Solution 6 - Php

$dataProvider = new ActiveDataProvider([ 
    'query' => $query, 
    'sort'=> ['defaultOrder' => ['iUserId'=>SORT_ASC]] 
]);

Solution 7 - Php

As stated in the guide, you must specify the sorting behaviors of a data provider by configuring its sort properties which correspond to the configurations for yii\data\Sort

$dataProvider = new ActiveDataProvider([
         'query' => $query,
         'sort'=> ['defaultOrder' => ['topic_order' => SORT_ASC]],
     ]);

Solution 8 - Php

you can modify search model like this

$dataProvider = new ActiveDataProvider([
        'query' => $query,
        'sort' => [
            'defaultOrder' => ['user_id ASC, document_id ASC']
        ]
    ]);

Solution 9 - Php

    $modelProduct 		= 	new Product();
    $shop_id 			= 	(int)Yii::$app->user->identity->shop_id;
	        
	$queryProduct  		=	$modelProduct->find()
							->where(['product.shop_id'	=> $shop_id]);
								
	
	$dataProviderProduct	=	new ActiveDataProvider([
									'query' 		=>	$queryProduct,
									 'pagination' => [ 'pageSize' => 10 ],
									'sort'=> ['defaultOrder' => ['id'=>SORT_DESC]]
								]);	

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionnsvView Question on Stackoverflow
Solution 1 - PhpAlexView Answer on Stackoverflow
Solution 2 - PhpKristīne GlodeView Answer on Stackoverflow
Solution 3 - PhpParth ChavdaView Answer on Stackoverflow
Solution 4 - PhpAndrey MatveevView Answer on Stackoverflow
Solution 5 - Phpuser210195View Answer on Stackoverflow
Solution 6 - PhpSuraj VaghelaView Answer on Stackoverflow
Solution 7 - PhpPatherView Answer on Stackoverflow
Solution 8 - Phpbrahmeswara rao KamineniView Answer on Stackoverflow
Solution 9 - Phpjagjit singhView Answer on Stackoverflow