Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CGridView custom column filter

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',
        ),
    ),
)); ?>
like image 373
Thu Ra Avatar asked Aug 07 '12 11:08

Thu Ra


2 Answers

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'),
    );
}
like image 68
Thu Ra Avatar answered Oct 04 '22 18:10

Thu Ra


First change:

'name'=>'$data->first_name',

to:

'name'=>'first_name',

In model's search method, you will have to add LIKE condition:

$model->addSearchCondition( 'CONCAT( first_name, " ", last_name )', $this->first_name );
like image 35
Boris Belenski Avatar answered Oct 04 '22 18:10

Boris Belenski