CGridView custom column filter

Thu Ra picture Thu Ra · Aug 7, 2012 · Viewed 10.8k times · Source

Q : how to create filter for my gridview?

status : customer name = first_name . last_name

This is my grid view

<?php $this->widget('zii.widgets.grid.CGridView', array(
    'id'=>'customer-grid',
    'dataProvider'=>$model->search(),
    'filter'=>$model,
    'columns'=>array(
        array(
              'header'=>'Customer Name',
              'name'=>'$data->first_name',
              'value'=>'$data->first_name.\' \'.$data->last_name',
              ),        
        'company_name',
        'country',
        'state',
        'city',     
        'address1',         
        'phone1',       
        'email',        
        array('name' => 'company_id',
               'value'=>'$data->companies->name',
               'filter'=>CHtml::listData($records, 'id', 'name'),
        ),
        array(
            'class'=>'CButtonColumn',
        ),
    ),
)); ?>

Answer

Thu Ra picture Thu Ra · Aug 8, 2012

create a var at model

class Customer extends CActiveRecord
{
    public $customer_name;
    public function search()
    {            
        $criteria->compare('CONCAT(first_name, \' \', last_name)',$this->customer_name,true);            
    }
}

at view

<?php $this->widget('zii.widgets.grid.CGridView', array(
        'id'=>'customer-grid',
        'dataProvider'=>$model->search(),
        'filter'=>$model,
        'columns'=>array(
            array(           
                'name'=>'customer_name',
                'value'=>'ucwords($data->first_name.\' \'.$data->last_name)',
                  ),        
            'company_name',
            'country',
            'state',
            'city', 
            'address1',
            'phone1',
            'email',
            array(
                'class'=>'CButtonColumn',
            ),
        ),
    )); ?>

And don't forget to declare the new attribute as 'safe' in the rules() method of your model, or your input will not be considered

public function rules()
{
    return array(
    /* ... */
        array('customer_name', 'safe', 'on'=>'search'),
    );
}