This behavior lets a model return CActiveDataProviders for its relations in a dynamic way.
Requirements ¶
Yii 1.1 or above
Usage ¶
Often you find yourself in the need to show a list of a model related objects, and of course you'll want to use built-in tools like CGridView or CListView to display this data.
But this Widgets require a CDataProvider to render its items, needing you write something like the following in your controller:
<?php
//BarController.php
public function actionFoo(){
$model = $this->loadModel();
$criteria = new CDbCriteria;
$criteria->condition = "parent_id = {$model->id}";
$dataProvider = new CActiveDataProvider('relatedModel', array(
'criteria' => $criteria,
));
$this->render('view', array(
'model' => $model,
'dataProvider' => $dataProvider,
));
}
//view.php
$this->widget('zii.widgets.grid.CGridView', array('dataProvider' => $dataProvider));
?>
Wouldn't it be easier if you could do this instead?
<?php
//BarController.php
public function actionFoo(){
$model = $this->loadModel();
$this->render('view', array(
'model' => $model,
));
}
//view.php
$this->widget('zii.widgets.grid.CGridView', array('dataProvider' => $model->getDataProvider('relatedModel')));
?>
Installation ¶
- copy DynamicDataProviderBehavior.php to your 'components' folder (so that it is automatically loaded)
- Install it like any other behavior in your models: behaviors()
public function behaviors()
{
return array(
'dataProvider'=>array(
'class'=>'DynamicDataProviderBehavior',
),
);
}
- Use it:
<?php
//view.php
$this->widget('zii.widgets.grid.CGridView', array('dataProvider' => $model->getDataProvider('relatedModel')));
?>
I love everything about this extension, but....
For some reason the misspelling of 'dynamic' is really bothering me! Was it on purpose?
Yeah!
Yeah! In Like to bother people on purpose :)
pd: not really, my english just sucks
Error when primary key column is not named 'ID'
I have to change like 30 to
php $criteria->compare($relations[$relation][2], $this->owner->{$this->owner->getTableSchema()->primaryKey});
For it to work.
Not working with MANY_MANY
I offer the following code change to make this extension support MANY_MANY relations (from line 79):
if ($type == CActiveRecord::MANY_MANY) { preg_match('/^([a-z_-]+)\(([a-z_-]+),\s?([a-z_-]+)\)$/', $foreignKey, $matches); list(,$cross_table,$key1,$key2) = $matches; $criteria->addCondition("t.".CActiveRecord::model($relatedModel)->getTableSchema()->primaryKey." IN (SELECT $key2 FROM $cross_table WHERE $key1=".$this->owner->{$this->owner->getTableSchema()->primaryKey}.")"); } else { $criteria->compare("t.".$foreignKey, $this->owner->{$this->owner->getTableSchema()->primaryKey}); };
If you have any questions, please ask in the forum instead.
Signup or Login in order to comment.