T
T
twopizza2016-05-21 11:06:58
Yii
twopizza, 2016-05-21 11:06:58

How to sort by calculated fields in GridView?

By default, only those fields that are in the model table are available for sorting in the GridView.
The task is to sort by calculated fields. There is a tutorial, tyk , but it just gets the value through the link and pushes it into setSort in the search method:

$dataProvider->setSort([
        'attributes' => [
            'id',
            'countryName' => [
                'asc' => ['tbl_country.country_name' => SORT_ASC],
                'desc' => ['tbl_country.country_name' => SORT_DESC],
                'label' => 'Country Name'
            ]
        ]
    ]);

In my case, the values ​​should be calculated based on the related data.
Solved the problem in the following way. In the search method:
$query = Model::find();
$select = ['*', '(SELECT %MY QUERY WITH COUNT JOINS ETC%) AS calculatedField'];
$query->select($select);
$dataProvider = new ActiveDataProvider([
    'query' => $query,
]);
$dataProvider->setSort([
    'attributes'=>[
        'calculatedField' => [
            'asc'=>['calculatedField'=>SORT_ASC,],
            'desc'=>['calculatedField'=>SORT_DESC],
        ],
    ]
]);

Are there any more elegant solutions? Or is there something in the GridView itself for this?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question