Question

I have a calculated column I wanna have sortable. I have a get method for it...

public function getCur_margin() {
        return number_format(($this->store_cost / $this->store_price) / $this->store_cost * 100, 2) . '%';
    }

And I followed this thread...

CGridview custom field sortable

But now it's looking for an actual column in the database. How can I fetch a field using <calculations> AS cur_margin only temporarily for this CActiveDataProvider?

Here is the controller code for the provider:

$dataProvider = new CActiveDataProvider('Products', array(
    'criteria' => array(
        'condition' => 'store_id IN (SELECT `id` FROM `stores` WHERE `user_id` = ' . Yii::app()->user->id . ')',
    ),
    'pagination' => array(
        'pageSize' => 15,
    ),
    'sort'=>array(
        'attributes'=>array(
            'cur_margin' => array(
                'asc' => 'cur_margin ASC',
                'desc' => 'cur_margin DESC',
            ),
        ),
    ),
));
Was it helpful?

Solution

Have you tried to specify your custom field in select property of CDbCriteria?

'select' => array(
    ...,   // fields to select
    '(<calculations>) AS cur_margin'
)

You don't have to declare getCur_margin() method then but only declare a public $cur_margin member in your model. All required calculations will be done in SQL query.

You can also refer to this thread as an example.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top