sortingyii2

YII2: custom sorting in search model


Please, help me with such a problem:

1) I have default search model of Users.

2) I need a list of users. And first in this list always must be user with login 'admin', and second - with login 'finance', and then all others sorted by id.

My method in UserController

public function actionUsersList() {
           $searchModel = new UserSearch();
    $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

    return $this->renderPartial('users-list', [
        'searchModel' => $searchModel,
        'dataProvider' => $dataProvider,
    ]);
}

As I understood I have to change params of search in this line, to add sort conditions

$dataProvider = $searchModel->search(Yii::$app->request->queryParams);

But how exactly can I do this?


Solution

  • You can do that by adding following code to your action:

    $dataProvider->sort->attributes['id'] = [
        'asc' => [
            new \yii\db\Expression("FIELD(login, 'finance', 'admin') DESC"),
            'id' => SORT_ASC,
         ],
         'desc' => [
             new \yii\db\Expression("FIELD(login, 'finance', 'admin') DESC"),
             'id' => SORT_DESC,
         ],
         'label' => $searchModel->getAttributeLabel('id'),
    ];
    
    $dataProvider->sort->defaultOrder = ['id' => SORT_ASC];
    

    The field function returns the position of first parameter among other parameters or 0 if the value is not present among them. So for 'admin' it will return 2, for 'finance' 1 and for others 0. If you order DESC by that you will get the required order.

    Other option is to add this definitions for sort into the search method of UserSearch model as suggested in mahsaa's answer. It depenends if you want to use this sorting in different actions.