Yii Framework Forum

Sorting CGridView on computed column

(tabularasa) #1

Hi, I create a CGridView obtained from a CArrayDataProvider containing a username and an email, and a table with books owned by this user and read books by this.
The grid is formed like this:
‘dataProvider’ => $dataProvider,
‘columns’ => [
[‘name’ => ‘username’, ‘value’ => $data->username],
[‘name’ => ‘ratio’m ‘value’ => Books::convRatio($data->userId)’]

very simplified ofcourse. Convratio is a function in the Books model which computes the read books vs owned books ratio. This all displays fine, so it’s all working.
But my question is now: I would like to have the view sorted by the read ratio, so the person who read the most books he owns at the top.
How do I achieve this? I already searched the forums but nothing seems to suit my exact needs.

(Softark) #2

Books::convRatio($data->userId) will work fine for displaying, but it won’t work for sorting.
In order to sort the data by the ratio, it should be already present in the data. You have to do the calculation of the ratio and include the calculated value in the array of data when you are constructing CArrayDataProvider.