Search code examples
sortingyiicgridview

yii CGridView initial sort


Is there any way to set an initial sorting a CGridView? I have a DB table that contains: id | name | description | create_time... In my CGridView I want my data to be shown without the id (this can be done by setting columns in CGridView but I would like to know if there is any other method to eliminate this fields from dataProvider) and I want to have my data sorted after name ASC. How can I do this because it always sort after id and I can't set a criteria for CGridView?


Solution

  • You can define a default order in your model respectively the CActiveDataProvider. The following snippet sorts by the column SortMeColumn by default.

    public function search()
    {
      $criteria = new CDbCriteria;
      $criteria->compare('ID', $this->ID, true);
      $criteria->compare('SortMeColumn', $this->SortMeColumn, true);
    
      return new CActiveDataProvider($this,
            array(
               'criteria' => $criteria,
               'sort' => array(
                  'defaultOrder' => array(
                     'SortMeColumn' => CSort::SORT_DESC
                  ),
               ),
            ));
    }
    

    See CSort for reference.