Unable to sort related table in CListView

Hi,

I have a problem sorting my list (from a related table) in CListView.

From views/place/view.php,I would like a display all the locations related to a place.

I’m able to list the locations but unable to sort by location name. Please help. Thanks

My tables are as follows:




      +-------+      +------------+     +--------+

      |place  |      |  outlet    |     |location|

      +-------+      +------------+     +--------+

      |       |      |id          |     |        |

      |id     |-----<|placeID     |  +--|id      |

      |name   |      |locationID  |>-+  |name    |

      +-------+      +------------+     +--------+



My code is as follows:




	$condition="placeID ='$model->id'";	

	

	$criteria->condition=$condition;

	$criteria->order = 'id';


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

		'criteria'=>$criteria,

		'pagination'=>array('pageSize'=>30),


	));


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

            'dataProvider'=>$dataProvider,

            'itemView'=>'_viewoutlet',   

            'enableSorting'=>'true',

	    'sortableAttributes'=>array(

                'locationID',   //what do I need to insert to sort by location name instead of locationID?

	    ),

	));



You need to define the sorting in your CActiveDataProvider.

See: http://www.yiiframework.com/doc/api/1.1/CSort

Basically, you just need to pass it another array value:




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

        'criteria'=>$criteria,

        'pagination'=>array('pageSize'=>30),

        'sort'=>array(

             'attributes'=>array(

                 'location'=>array(

                     'asc'=>'location.name',

                     'desc'=>'location.name DESC',

                     'label'=>'Location',

                     'default'=>'asc',

                 ),

                 '*', 

             )

        )  

    ));



Thanks Dana for your reply but unfortunately it still does not sort by location name. It is still sorted by id. Anywhere else I should check?

You’re telling it to order by id in your criteria, you need to remove that line.

Thanks again, Dana . You have been much help. I’ve tried to remove all the unnecessary codes but it didn’t help.

Finally after taking your tips and http://www.yiiframework.com/doc/api/1.1/CDbCriteria into consideration, I’ve got a breakthrough by adding the following codes:




$condition="placeID ='$model->id'";	

$criteria = new CDbCriteria;

$criteria->with = array('location');

$criteria->together = true;

$criteria->select = array('id');

$criteria->condition=$condition;

$criteria->order = 'location.name ASC';