multiple CActiveDataProviders in one CGridView

You are viewing revision #3 of this wiki article.
This is the latest version of this article.
You may want to see the changes made in this revision.

« previous (#2)

There is a few cases that you want more of one CActiveDataProvider displayed in one CGrideView How to do that?

Obviusly the CActiveDataProviders have to same schema (contains same columns)

In your controller set the two (or more) CActiveDataProvider like that

$prov1 = new CActiveDataProvider('Post', array(
	'criteria' => array(
		'condition' => 'id<3'
	)
));

$prov2 = new CActiveDataProvider('Post', array(
	'criteria' => array(
		'condition' => 'id>3'
	)
));

Obviusly in this case you could use 'condition' => 'id>3 or id<3' buτ let us assume we want the CActiveDataProvider seperated for another purpose.

Now we have to merge these data in one Provider through array

$records = array();

for ($i = 0; $i < $prov1->totalItemCount; $i++) {
	$data = $prov1->data[$i];
	array_push($records, $data);
}
for ($i = 0; $i < $prov2->totalItemCount; $i++) {
	$data = $prov2->data[$i];
	array_push($records, $data);
}
//or you could use $records=array_merge($prov1->data , $prov2->data);

$provAll = new CArrayDataProvider($records,
	array(
		'sort' => array( //optional and sortring
			'attributes' => array(
				'id', 
				'title'
			),
		),
		'pagination' => array('pageSize' => 10) //optional add a pagination
	)
);

//render a view
$this->render('custom',array('provAll' => $provAll));

in custom.php add the CGridView widget

$this->widget('zii.widgets.grid.CGridView', array(
	'dataProvider' => $provAll,
	'columns' => array('id', 'title'),
));

Both of two CActiveDataProvider data will be displayed in CGridView