Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert model data objects array to dataProvider

Suppose I have model User which have many to many relation to itself named as friends. so $user->friends (or $model->friends in view) gives me an array of User objects. I wanted to display the friends as gridview. But CGridView data as dataProvider object. Googling for it found the way to convert array of model objects to dataProvider object as given below.

$this->widget('zii.widgets.grid.CGridView', array(
    'id' => 'gridUser',
    'dataProvider' => new CArrayDataProvider($model->friends, array()),
));

Now using this I get an error

Property "User.id" is not defined.

UPDATE

public function relations()
{
    return array(
         'friends' => array(self::MANY_MANY, 'User', 'friendship(user_id, friend_id)'),
    );
}
like image 497
Prashanth Shyamprasad Avatar asked Jan 03 '13 07:01

Prashanth Shyamprasad


Video Answer


2 Answers

I use two stage building the provider shown below. But I found that it gives you trouble in terms of Pagination. I have not bothered to resolve that problem since am doing other things

$dataProvider =  new CArrayDataProvider('User');
$dataProvider->setData($model->friends);
$this->widget('zii.widgets.grid.CGridView', array(
    'id' => 'gridUser',
    'dataProvider' =>$dataProvider,
));

That being said, your code should work (see the example below from API docs). I suspect there is wrong attribute in your relations than the provided code. Re-check the relation definition if it is ok

From Yii docs:

$rawData=Yii::app()->db->createCommand('SELECT * FROM tbl_user')->queryAll();
// or using: $rawData=User::model()->findAll(); <--this better represents your question
$dataProvider=new CArrayDataProvider($rawData, array(
    'id'=>'user',
    'sort'=>array(
        'attributes'=>array(
             'id', 'username', 'email',
        ),
    ),
    'pagination'=>array(
        'pageSize'=>10,
    ),
));
like image 200
Stefano Mtangoo Avatar answered Sep 23 '22 17:09

Stefano Mtangoo


Got it :) , i can use CActiveDataProvider instead of CArrayDataProvider as given below

$this->widget('zii.widgets.grid.CGridView', array(
    'id' => 'gridUser',
    'dataProvider' => new CActiveDataProvider('User', array(
            'data'=>$model->friends,
    )),
    //...... columns display list.....
));

Anyways thanks for the reply @Stefano

like image 27
Prashanth Shyamprasad Avatar answered Sep 20 '22 17:09

Prashanth Shyamprasad