yii CGridView dataprovider and filter

12,654

Solution 1

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

Solution 2

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,
    ));
}
Share:
12,654
Developerium
Author by

Developerium

Instagram LinkedIn

Updated on June 28, 2022

Comments

  • Developerium
    Developerium almost 2 years

    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.

  • Developerium
    Developerium over 10 years
    if one of the criterias has a "join" property and another a "with" property, you would be in trouble, right?
  • Developerium
    Developerium over 10 years
    where is the new $criteria used?(it's not used in this method!)