Adding Custom Sorting Attributes To Default Ones

I have a model with a virtual (calculated) column which I need to make sortable in admin’s CGridView. I have created a new CSort object with required SQL statements. Now if I add the sort object into CActiveDataProvider:


new CActiveDataProvider($this, array(

			'criteria'=>$criteria,

			'sort' => $sort,

		));

I got the grid with only this one column sortable, but all the others looses the sorting option. I understand that I can make them sortable by adding them to my custom CSort object, but this is counterproductive because requires to duplicate names of the fields, and keep an eye on this portion of code to be synchronized with other columns, which may be added in the future.

So the question is - how to add custom sorting attributes to default ones, which CActiveDataProvider provides for db columns?

I have tried the following: first - create CActiveDataProvider $result without the ‘sort’ attribute, and second - merge arrays:


$result = new CActiveDataProvider($this, array(

			'criteria'=>$criteria,

		));

$result->sort->attributes = array_merge($result->sort->attributes, ...

This did not work, because $result->sort->attributes remains undefined even after the CActiveDataProvider object is created.

Thanks in advance.

You can use something like this




$sorter = new CSort;

$sorter->defaultOrder = 'id';

$sorter->attributes = array(

	'id'=>'id',

	'user_id'=>'user_id',

	'first_name'=>'first_name', 

	'middle_name'=>'middle_name',

	'last_name'=>'last_name',

/* the follow is a custom sorter */

	'full_name'=>array(

		'asc'=>'first_name, middle_name, last_name',

		'desc'=>'first_name DESC, middle_name DESC, last_name DESC',

	),

/* */

	'genger'=>'genger',

	'birthday'=>'birthday',

	'create_time'=>'create_time',

	'update_time'=>'update_time',

);


$result = CActiveDataProvider($this, array(

	'criteria'=>$criteria,

	'sort'=>$sorter

));



You can include the asterisk (*) in your $sort->attributes to preserve existing sort attributes of your model

http://www.yiiframework.com/doc/api/1.1/CSort#attributes-detail




    $sort = new CSort();

    $sort->attributes = array(

        *, // preserve sorting capability

        'virtualColumn'=>array(

            'asc'=>'virtualColumn ASC',

            'desc'=>'virtualColumn DESC',

        ),

    );


    return new CActiveDataProvider($this, array(

        'criteria'=>$criteria,

        'sort'=>$sort,

    ));