Search code examples
phpyiicgridview

How to i search and sort by use zii.widgets.grid.CGridView when my column there is not in table and attributes?


I want to show list of my attributes (id, name, price, discount) and (total_price)column that is not an attribute.

when I use this code, it shows table of data but I can not search or sort in column (total_price)

Can anyone hep me?

<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'product-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
    'id',
    'name',
    array(
            'header' =>'Price',
            'name'=>'price',
            'value'=>'$data->price',
    ),
    array(
            'header' =>'Discount',
            'name'=>'discount',
            'value'=>'$data->discount',
    ),
    array(
            'header' =>'total price',// total price doesn't save in Data Base
            'name'=>'total_price',
            'value'=>'total_price - (total_price * $data->discount/100)',
    ),
    array(
        'class'=>'CButtonColumn',
    ),
),

));
?>


Solution

  • You can put on $model->search() method this:

    $criteria=new CDbCriteria;
    
    $criteria->select = "t.*, t.price - (t.price * t.discount/100) as total_price";
    
    // EDITED: Added for Sort:
    $sort = new CSort();
    $sort->attributes = array(
                            'defaultOrder'=>'name ASC',
                            'total_price'=>array(
                                'asc'=>'total_price ASC',
                                'desc'=>'total_price DESC',
                              ),
                              '*', // Add order in the other fields.
                        );
    
    return new CActiveDataProvider($this, array(
            'criteria'=>$criteria,
            'sort'=>$sort, // Added to sort.
    );
    

    And create a not persistence attribute on "Product" model Class:

    public $total_price;
    

    Finally put 'total_price' on rules() in array with ('safe', 'on'=>'search'), something like this:

    array('id, name, price, discount, total_price', 'safe', 'on'=>'search'),