Sorting CGridView by relation

I feel like this is incredibly obvious but it’s just not clicking for me right now…I want to have the default order for a CGridView to be based on a relation’s atrribute…




//relation

return array(

    'engine' => array(self::BELONGS_TO,'Engines','eid','order'=>'name'),

);



In my CGridView I display as one of the columns the engine’s name, like so:




array(

    'name'=>'engine',

    'value'=>'$data->engine->name'

),



How do I get it so that the grid is sorted by default by that name attribute? Thanks.

Hello,

I have ever made something like this before and here is how I made it works.

In the relation:




return array(

   'distributor' => array(self::BELONGS_TO, 'Distributor', 'distributor_id'),

);



In search procedure:




// set sort options

$sort = new CSort;

$sort->attributes = array(

   ... (the other fields)

   'distributorName'=>array(

      'asc'=>'distributor.name',

      'desc'=>'distributor.name desc',

  ),

);

$sort->defaultOrder = 'distributor.name';


return new CActiveDataProvider(get_class($this), array(

  'criteria'=>$criteria,

  'sort'=>$sort,

));



And in CGridView:




array(

  'name'=>'distributorName',

  'value'=>'$data->distributor->name',			

)



Not sure if this is the best solution, but hopefully this can give a click to you. :)

maybe by adding an order criteria in fuction search in models…

like this


$criteria=new CDbCriteria;

$criteria->order = "engine.name";