yii sort by a custom attribute

£可爱£侵袭症+ 提交于 2019-12-11 09:59:59

问题


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:


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.



来源:https://stackoverflow.com/questions/10890507/yii-sort-by-a-custom-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!