Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override default sort for ActiveDataProvider in Yii2

Tags:

yii2

I have a lot of models using created_time. And I want all of the GridViews to show the models sorted by created_time DESC.

Right now I write something like this

$dataProvider = new \yii\data\ActiveDataProvider([
        'query' => MyModel::find(),
        'sort' => [
            'defaultOrder' => [
                'created_time' => SORT_DESC
            ]
        ],
    ]);

Instead of writing all of sort configuration I tried ways below but nothing works.

  1. Using container

    \Yii::$container->set(\yii\data\ActiveDataProvider::class,
            [
        'sort' => [
            'defaultOrder' => [
                'created_time' => SORT_DESC
            ]
        ]
    ]);
    
  2. Overriding the sort in extended class.

    class ActiveDataProvider extends \yii\data\ActiveDataProvider {
    
        public $sort = [
            'defaultOrder' => [
                'created_time' => SORT_DESC
            ]
        ];
    
     }
    
  3. Overriding before init() in the extended class works, but it won't work if the instantiation tries to override again.

    class ActiveDataProvider extends \yii\data\ActiveDataProvider {
        public function init() {
            $this->sort = [
                'defaultOrder' => [
                    'created_time' => SORT_DESC
                ]
            ];
            parent::init();
        }
    
    }
    
    //but this won't work if I want to use the ascending
    $dataProvider = new \app\components\data\ActiveDataProvider([
        'query' => MyModel::find(),
        'sort' => [
            'defaultOrder' => [
                'created_time' => SORT_ASC
            ]
        ],
    ]);
    
like image 597
Eric Hancock Avatar asked Oct 12 '25 21:10

Eric Hancock


2 Answers

To do this for a single GridView, you can add 'defaultOrder' => ['created_time' => SORT_DESC] to the array that is accepted by setSort():

    $dataProvider->setSort([
        'attributes' => [
            'id',
            ...
        ],
        'defaultOrder' => ['created_time' => SORT_DESC]
    ]);
like image 171
deacs Avatar answered Oct 14 '25 14:10

deacs


You should do this for yii\data\Sort and not for yii\data\ActiveDataProvider. See the documentation to $sort property.

1) With container:

use Yii;

...

Yii::$container->set(\yii\data\Sort::className(),
    'defaultOrder' => [
        'created_time' => SORT_DESC,
    ],
]);

2) Overriding class:

class Sort extends yii\data\Sort
{
    public $defaultOrder' = [
        'created_time' => SORT_DESC,
    ];
}
like image 27
arogachev Avatar answered Oct 14 '25 13:10

arogachev