Yii Examples: Sorting Columns on a CGridView (using CActiveDataProvider)

Yii Examples: Sorting Columns on a CGridView (using CActiveDataProvider)

Last updated:

You should use a data provider like this to populate your CGridView, set up a default sorting order and enable column headers to turn into links which (actually) work to activate sorting.

The keys in $sort->attributes should match columns in the CGridView:

<?php
    $sort = new CSort;
    $sort->attributes = [
        'title' => [
            'asc' => 'title',
            'desc' => 'title desc',
        ],
        'last_modified'=>[
            'asc'=>"last_modified",
            'desc'=>"last_modified desc"
        ]
    ];

Setting the default order like this will cause the little arrow to show up! This helps your users know how you've ordered the results.

<?php

   // true means 'desc' and false means 'asc'
    $sort->defaultOrder = ['last_modified'=>true];

    // now use it in a `$dataProvider` to populate your CGridView!

    $dataProvider = new CActiveDataProvider($this, [
        'criteria' => $criteria,
        'sort'=>$sort
    ]);

You don't need to set all options if you just need defaultOrder, for example:

<?php
// Car is an ActiveRecord that has a datetime attribute called 'year'
$dp = new CActiveDataProvider('Car', [
            'pagination' => [
                'pageSize' => 20
]]);

// sort cars by descending year
$dp->sort->defaultOrder = [ 'year' => true ];

// now you can feed this data provider into a grid
// and your models will be correctly sorted