Using CGridView for a model's association
Asked Answered
I

2

7

I have a model with has_many association.

Let's just say Student has many Courses.

I'd like to show all courses of a particular student using CGridView.

Something like this:

$this->widget('zii.widgets.grid.CGridView', array(                                                 
  'dataProvider' => $model->courses,                                                             
  'columns'=>array(                                                                                                                                                                            
    'name',                                                                                                                                                                                  
  ),                                                                                                 
));

Also tried new CActiveDataProvider($model->courses) as dataProvider but still wont work.

Is there an easy way to do this? Or do I have to create a search criteria on the Course model with some criteria taken from the student model manually?

Imparipinnate answered 13/4, 2011 at 9:38 Comment(0)
G
13
  1. Get rid of the parentheses after courses

  2. Use an arraydataprovider

    $this->widget('zii.widgets.grid.CGridView', array(
      'dataProvider' => new CArrayDataProvider($model->courses, array()),
      'columns'=>array(
        'name',
      ), 
    ));
    
Ginger answered 13/4, 2011 at 16:31 Comment(0)
F
0

A few things to start off:

  1. I think it should be $model->courses instead of $model->courses()
  2. The reason that doesn't work anyway is that Yii's AR relations return an array of objects, not an actual DataProvider object

Anyway, I seem to remember struggling with this as well. I never really got it to work like I wanted it to. The closest I got was setting the 'data' variable in my dataProvider, but then the paging was broken in my ListView. It worked something like this:

$dataProvider=new CActiveDataProvider('Course', array(
  'data'=>$model->courses,
));

What I ended up doing was creating new criteria to pass in to my DataProvider that did the same thing as the relation. Like so:

$criteria=new CDbCriteria;
$criteria->join = "JOIN student_course_relation_table sc ON sc.course_id = t.id";
$criteria->compare('sc.student_id',$model->id);
$dataProvider=new CActiveDataProvider('Course', array(
  'criteria'=>$model->courses,
));

I'm assuming that you are using a MANY_MANY relationship with a join table. I hope this helps, even though I'm sure it's not quite what you want to do. If anyone has a better solution please share! I want to learn about it too! :)

Flamethrower answered 13/4, 2011 at 15:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.