Problem with sorting and filtering with CGridView and relational data

I’ve read all posts I can find on filtering and sorting CGridView and relational data. The problem I have is that I only seem to be able to do one or the other. Not both.

If for instance I have this:




$this->widget('zii.widgets.grid.CGridView', array(

	'dataProvider'=>$dataProvider,

	'filter'=>$model,

	'columns'=>array(

        'namn',

		array(

            'name' => 'kategori.kategori',

            'filter' => CHtml::listData(Kategori::model()->findAll(array('order'=>'kategori ASC')), 'kategori_id', 'kategori'),

            'value' => 'Kategori::Model()->FindByPk($data->kategori_id)->kategori',

        ),));



I get sort to work when I click the title but I don’t have any sorting. If I however change it to:




...

           'name' => 'kategori',

...



I get filtering but sorting throws me an sqlerror. If I change to this:




...

           'name' => 'kategori_id',

...



I get filtering and sorting but it doesn’t sort on the names in ‘kategori.kategori’ but on kategori_id.

Any help here is really appreciated!

Thanks, Dang

Sorting should be possible by defining an CSort object that can be used with the CActiveDataProvider. You should define something like this in the search() function of your model:




$criteria->with('kategori');


//.....criteria stuff goes here


$sort = new CSort;

$sort->defaultOrder = 'kategori.name ASC';

$sort->attributes = array(

                    'name'=>'kategori.name',

                );


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

                        'criteria'=>$criteria,

                        'sort'=>$sort

                ));

EDIT:

I just saw that you do not use the search() function in your examples. Just add the CSort to whatever function you are using instead. Just make sure you are sending the CSort object and the dataprovider to CGridView