1

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?

Aladdin Mhemed
  • 3,817
  • 9
  • 41
  • 56

1 Answers1

5

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.

Community
  • 1
  • 1
acorncom
  • 5,975
  • 1
  • 19
  • 31
  • that does not answer my question. of course, I can use beforeSave and store the count value in the database table, and then CSort will work. But is this the right thing to do? – Aladdin Mhemed Jun 05 '12 at 04:44
  • It's one of the tensions of virtual attributes / business logic. You shouldn't have to save the count value in your database to make it work though. If you have your count() value specified in your query, then it will work. – acorncom Jun 05 '12 at 09:03
  • Updated with a link that shows how to do this with more detail. – acorncom Jun 05 '12 at 09:08
  • 1
    Correct. I've just posted some sample code that shows how I do it for one of my sites. – acorncom Jun 06 '12 at 15:01