filteryiiyii-extensionscgridviewyii1.x

To remove empty option from filter in CgridView Filter -Yii1


I would like to remove the empty or first option of list data value. I have FruitList model and it has a list, so I need to prevent from users to select all.

But now the problem is the empty option that can let user to select all Fruits, so how can I remove.

This is my code

$this->widget('zii.widgets.grid.CGridView', array(
    'dataProvider'=>$dataProvider,
    'columns'=>array(

         array(
            'header' => 'Buyer',
            'name' => 'Buyer',
            'value' => 'customer_name',
            'filter' => $fruits
        ),
        array(
            'header' => 'Fruits',
            'name' => 'fruit_id',
            'value' => '$data->Buyers->FruitList->Name',
            'filter' => $fruits
        ),
        array(            
            'class'=>'CButtonColumn',
        ),
    ),
));

Solution

  • By default filters for CGridView renders dropdown with empty option to allow disabling filtering. But you can overwriting this behavior by providing your own dropdown as a filter:

    $this->widget('zii.widgets.grid.CGridView', array(
        'dataProvider'=>$dataProvider,
        'columns'=>array(
    
             array(
                'header' => 'Buyer',
                'name' => 'Buyer',
                'value' => 'customer_name',
                'filter' => CHtml::activeDropDownList($model, 'customer_name', $fruits),
            ),
            array(
                'header' => 'Fruits',
                'name' => 'fruit_id',
                'value' => '$data->Buyers->FruitList->Name',
                'filter' => CHtml::activeDropDownList($model, 'fruit_id', $fruits)
            ),
            array(            
                'class'=>'CButtonColumn',
            ),
        ),
    ));
    

    Make sure that you set default value for these filters in your model - something like this in your controller:

    // ...
    $model->fruit_id = FruitList::DEFAULT_ID;
    $model->customer_name = FruitList::DEFAULT_ID;
    if (isset($_GET['FruitList'])) {
        $model->setAttributes($_GET['FruitList']);
    }
    $dataProvider = $model->search();
    // ...