Yii Framework Forum: Newbie Question: How to best sort with CListView using relations - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

Newbie Question: How to best sort with CListView using relations Rate Topic: -----

#1 User is offline   stickdog 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 27
  • Joined: 29-April 10

Posted 02 June 2010 - 03:45 PM

I can't find any examples on the site showing how to use CListView to sort using the value of a related field?

For example, if my table is storing a user id, but I wish to use CListView to sort by the user name in the user table, how can I best implement this?

I've tried

<?php $this->widget('zii.widgets.CListView', array(
	'dataProvider'=>$dataProvider,
	'itemView'=>'_view',
        'sortableAttributes'=>array(
        'user_id.name',
    ),

)); ?>


and a number of other shot in the dark approaches, but obviously I am missing something very fundamental. Can anyone here point me in the right direction?

Thanks so much.
0

#2 User is offline   zaccaria 

  • Elite Member
  • PipPipPipPipPip
  • Yii
  • Group: Members
  • Posts: 2,232
  • Joined: 04-October 09
  • Location:Moscow

Posted 03 June 2010 - 05:53 AM

If you have the relation setted up, you can change the dataProvider like that:

$dataProvider->criteria->with('User'); //that works if you have the relation with users
$dataProvider->sort=array(
     'user.name', ... //all other fields
);


Using "with" CActiveRecord will fetch even the related table, so you can sort for field in user.
0

#3 User is offline   boydzethuong 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 13
  • Joined: 05-April 10

Posted 03 June 2010 - 11:49 PM

as far as I know, CDbCriteria do not have 'with' method, so this maybe throw an error.

maybe this will work:

$criteria->with = array(
	'user'=>array('select'=>'username'),
);
// then you have to declare in sort
return new CActiveDataProvider('Category', array(
	'criteria'=>$criteria,
	'sort'=>array(
		'attributes'=>array(
			'username'=>array(
				'asc'=>'username',
				'desc'=>'username DESC',
			),
// don't forget re-define the columns of 'Category' table bc it will be overwritten

0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users