multiple CActiveDataProviders in one CGridView

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

4 1
9 followers
Viewed: 24 343 times
Version: 1.1
Category: How-tos
Last updated by: Nashi
Created on: Jun 24, 2013
Last updated: 3 years ago
Update Article

Revisions

View all history

Related Articles