CGridView default sort

How can I specify the CGridView default sort?

I want that as soon as the page finishes loading, the grid should be sorted alphabetically by a specific column.

Of course the user can later change that order by clicking in the column headers.

In your data provider, you can use the "defaultOrder" property of CSort. For example:




$dataProvider=new CActiveDataProvider('Example', array(

  'sort'=>array(

    'defaultOrder'=>'title ASC',

  )

));



Thanks for the answer :lol:

Hello,

I can add default sort column to my CGridView, but the default sort icon does not display on column header.

Can anyone help me?

Thanks

I just ran into this same issue, and will document the solution here in case anyone else is searching the forums for a solution. As of version 1.1.3, you can make defaultOrder an array, which will in turn populate the directions property, which will make the arrow direction indicator icons show up like you want:


$dataProvider=new CActiveDataProvider('Example', array(

  'sort'=>array(

    'defaultOrder'=>array(

      'title'=>false

    )

  )

));

The value of the column name key indicates direction - false for ASC, true for DESC.

This solved my problem. Thanks! B)

Thanks - I was scratching my head over getting the order arrows to display on page load. Note that from version 1.1.10, the constants CSort::SORT_ASC and CSort::SORT_DESC are available for convenience/readability.

there is no need to complicate, just:

$model=new YourModel();

$model->dbCriteria->order=‘title ASC’;

shakedbrains this!

This works! Great suggestion.

Many thanks

Thanks!




$dataProvider=new CActiveDataProvider('Example', array(

  'sort'=>array(

    'defaultOrder'=>array(

      'title'=>false

    )

  )

));



That’s very useful for me…Thank You




$sort=new CSort;

        $sort->attributes=array(

            'name' => array( "asc"=>'id', "desc" => 'id desc'),

        );

        $sort->defaultOrder = 'id desc';


$dataProvider=new CActiveDataProvider('Example', array(

  'sort'=>$sort

));



Please don’t use this because if you click in the name of the grid column use to order the generated sql put twice order clause and fail.

use CActiveDataProvider->sort->defaultOrder=‘title ASC’