1

This question directly follow this other

I have this tables: Groups, Users, Reports

Relations: Groups 1 -> N Users ** and ** Users 1 -> N Reports

I already have this relation In Report model:

'user' => array(self::BELONGS_TO, 'Users', 'userId'),

And this in User model

'group' => array(self::BELONGS_TO, 'Gruppi', 'groupId'),

In Report Model I have this:

$criteria=new CDbCriteria;
$criteria->with = array ('user');

In the admin view of report I'm using a CGridView.

I'm using user.group.name for showing group name, but how to search (by DropDown) and sort !?

Community
  • 1
  • 1
realtebo
  • 23,922
  • 37
  • 112
  • 189
  • 1
    for this, check : http://www.yiiframework.com/wiki/281/searching-and-sorting-by-related-model-in-cgridview/ – bool.dev Oct 13 '12 at 13:25
  • 1
    see my answer, I've extended the wiki solution adding the combo for searching, and extended the solution to cover the two-level relation problem ... – realtebo Oct 13 '12 at 13:28
  • 1
    ok, that's nice, and it's ok to accept your own answer. – bool.dev Oct 13 '12 at 13:32
  • Thanks, I was waiting for a confirm the my answer was valid and 'good code pratice'. (I must wait one onther day, and I'll can do it) – realtebo Oct 14 '12 at 15:07

1 Answers1

1

In admin view, instead of user.group.name, i'm using

array (
        'name' => 'groupId',
        'value' => '$data->user->group->name',
        'filter' => Chtml::listData( Groups::model()->findAll() ,'id','name')
    ),

In Report model I added a class field

public $groupId;

In Report rules

    array('groupId','safe','on'=>'search'),

In Report search

....
$criteria->with = array ('user.group');
....
$criteria->compare('user.groupId',$this->groupId);
....
[in sort array]
'groupId'=>array(
            'asc' =>'group.name',
                'desc'=>'group.name DESC',
 ),

In this way I can search, and sort, by group name !

I hope this post can be usefull to someon

realtebo
  • 23,922
  • 37
  • 112
  • 189