0

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',
            ),
        ),
    ),
));
Community
  • 1
  • 1
casraf
  • 21,085
  • 9
  • 56
  • 91
  • This might help: http://www.mrsoundless.com/php/yii/searching-and-sorting-a-column-from-a-related-table-in-a-cgridview/ – MrSoundless Jun 20 '13 at 11:41

1 Answers1

3

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.

ezze
  • 3,933
  • 2
  • 34
  • 58