Search code examples
yiicgridview

yii CGridView dataprovider and filter


I know we can show a gridview with a model and it's search method and filter the results, but can we make a gridview with another dataprovider and another model like this and filter its results? Does filter needs to be a part of dataprovider?

$attr = Yii::app()->request->getParam($name);

$model = new User('search');
$model->unsetAttributes();
$model->setAttributes($attr);

$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider' => $myDataProvider,
'filter' => $model,
'columns' => array(
    array(
        'name' => 'username',
        'type' => 'raw',
        'value' => 'CHtml::encode($data->username)'
    ),
    array(
        'name' => 'email',
        'type' => 'raw',
    ),
),

));

The above code doesn't work and I need to add a filter on a previously made data provider.

Btw $attr has a valid data, but grid is not filtered.


Solution

  • $model doesn't affect $myDataProvider since the data provider is not obtained using this model.

    $model->search() returns a CActiveDataProvider which contains a CDbCriteria instance. Different CDbCriteria can be combined using mergeWith(). So if you would like the data to be filtered using the values from the $model

    ...
    $model->setAttributes($attr);
    
    $newDataProvider=$model->search();
    $myDataProvider->criteria->mergeWith($newDataProvider->criteria);
    
    $this->widget('zii.widgets.grid.CGridView', array(
    ...