Question

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.

Was it helpful?

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(
...

OTHER TIPS

Filter does not need to be a part of dataprovider, but data provider needs to take the model into account, if you want to use it for filtering.

The way this is done by default is to create the data provider using search method on your model, which sets conditions of your data provider based on model values, like so:

'dataProvider' => $model->search()

There is nothing preventing you from creating different data provider, for example:

'dataProvider' => $model->createAnotherDataProvider()

And in your User model:

public function createAnotherDataProvider() {
{
    // create your second data provider here 
    // with filtering based on model's attributes, e.g.:

    $criteria = new CDbCriteria;
    $criteria->compare('someAttribute', $this->someAttribute);

    return new CActiveDataProvider('User', array(
        'criteria' => $criteria,
    ));
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top