CGridView custom column filter

10,847

Solution 1

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'),
    );
}

Solution 2

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 );
Share:
10,847
Thu Ra
Author by

Thu Ra

Updated on June 07, 2022

Comments

  • Thu Ra
    Thu Ra over 1 year

    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',
            ),
        ),
    )); ?>