Home > yii framework > Using filters with CGridView and CArrayDataProvider

Using filters with CGridView and CArrayDataProvider

To use filter in CArrayDataProvide we must specify our own model to handle the filter. This is the example

Model

/**
 * Filterform to use filters in combination with CArrayDataProvider and CGridView
 */
class FiltersForm extends CFormModel
{
    public $filters = array();
 
    /**
     * Override magic getter for filters
     */
    public function __get($name)
    {
        if(!array_key_exists($name, $this->filters))
            $this->filters[$name] = null;
        return $this->filters[$name];
    }
 
    /**
     * Filter input array by key value pairs
     * @param array $data rawData
     * @return array filtered data array
     */
    public function filter(array $data)
    {
        foreach($data AS $rowIndex => $row) {
            foreach($this->filters AS $key => $value) {
                // unset if filter is set, but doesn't match
                if(array_key_exists($key, $row) AND !empty($value)) {
                    if(stripos($row[$key], $value) === false)
                        unset($data[$rowIndex]);
                }
            }
        }
        return $data;
    }
}

Controller

// Create filter model and set properties
$filtersForm=new FiltersForm;
if (isset($_GET['FiltersForm']))
    $filtersForm->filters=$_GET['FiltersForm'];
 
// Get rawData and create dataProvider
$rawData=User::model()->findAll();
$dataProvider=new CArrayDataProvider($rawData);
 
// Render
$this->render('index', array(
    'filtersForm' => $filtersForm,
    'dataProvider' => $dataProvider,
));

View

$columns = array(
    array(
        'header'=>CHtml::encode('Name'),
        'name'=>'username',
        'value'=>'$data->username',
    ),
    array(
        'header'=>CHtml::encode('Organisation'),
        'name'=>'organisation',
        'value'=>'$data->organisation',
    ),
);
 
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'area-grid',
'dataProvider'=>$dataProvider,
    'columns'=>$columns,
    'filter'=>$filtersForm,
));

Advertisement
Categories: yii framework
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.