CGridview to provide multiple sort

I encountered a nice functionality in some grid based interfaces, i.e. the possibility to sub-sort on a column by [Ctrl]-clicking a column title.

So if my gridview -which is displaying names and addresses- is sorted on City, I could [Ctrl]-click on the Name column to have it sorted primarily on City and within that on Name.

Did anybody solve this puzzle within Yii/Cgridview? I searched but didn’t find.

Is nobody interested? Or is it too obvious?

I think the only way is to extend the zii/widgets/grid/CGridView.php class and write your own functions for multiply sort.

I was afraid that would be the case. I’ll post it here if I manage.

Well it was too obvious alltogether!!

Just add multiSort=true to your dataprovider, like so:




return new CActiveDataProvider($this, array(

    'criteria' => $criteria,

    'sort'=>array(

	'defaultOrder'=>'name ASC',

	'multiSort'=>true,

    ),

));



It provides a basic multisort on the Gridview right away. Takes a little getting used to, but hey! just one line of code.

(It took me a few hours to find it in the docs, though.)

it’s nice… useful :)

The multisort is nice, but has a slighly different logic:

if you click on name and then on surname, you will get the order by surname and the name.

That’s the opposite than you said.

The trick of ctrl+click can be achived with a simple js hack, you have to read the url on the button clicked and switch the order of the sort (more precisely, to put the first item at the bottom).

Thanks for the tip Zaccaria.

I don’t care too much about the Ctrl, so I hacked extended CSort.

There’s a line in the link function in CSort.php saying




$directions=array_merge(array($attribute=>$descending),$directions);



I changed that to




$directions=array_merge($directions, array($attribute=>$descending));



This way it feels a bit more intuitive.

Can any one know how to display sorting numbers so I know that sorting order!

Thanks in advance

Almost six years later…

If you are looking for this functionality in Yii2, it is here!

$dataProvider->sort->enableMultiSort=true;