yii sort by a custom attribute

5.3k views Asked by At

In my Vacation model Vac I have this function

public function getVacCount(){

this function returns how many days there are in one vacation.

and I want to add a custom column to the cgridview like this:

   <?php
    $this->widget('zii.widgets.grid.CGridView', array(
            ...
            array(
                'name' => 'count',
                'value' => '$data->getVacPeriod()'
            ),
            ...
        ),
    ));
    ?>

it works fine. but I don't know how can I sort upon this custom attribute. I tried to use CSort but it does not work. any idea?

1

There are 1 answers

4
acorncom On BEST ANSWER

To use CSort for sorting, you'll need to convert your vacation function into a SQL query and then stash the results in a public variable in your model.

CSort only works with SQL statements/functions, as underneath it's using ORDER BY to do all the sorting.

More info (and demo code) available here

Here's a sample of how I'm doing it on a site of mine:

$criteria->select = array(
        "*",
        new CDbExpression("IF(survey.RequestDate, survey.RequestDate, SurveyCompleteDate) AS SurveyDate")
    );

This then allows me to do this type of filter:

return new CActiveDataProvider($this, array(
    'criteria' => $criteria,
    'sort'=>array(
        'attributes'=>array(
            'SurveyDate' => array(
                'asc' => 'SurveyDate',
                'desc' => 'SurveyDate DESC',
            ),
            '*',
        ),
    ),
);

Note: you'll also need a public variable defined in your model to hold the results of the CDbExpression that you're doing. Mine is called SurveyDate.