Kailas
Kailas

Reputation: 3231

Yii1 CGridView - SUM of Custom Column Value in footer

I want Sum of a custom column value in footer

GridView Code

$this->widget('zii.widgets.grid.CGridView', array(
    'id'=>'booking-grid',
    'dataProvider'=>$model->search(),
    'columns'=>array(
         array(
             'name'=>'name',
             'header'=>'User Name',
             'value'=>'$data->booking_id',
             'filter'=>false,
             'footer'=>'Total',
             'footerHtmlOptions'=>array('class'=>'grid-footer'),
         ),
         array(
             'name'=>'id',
             'header'=>'User Fee',
             'value'=> array($model,'GetUserFee'),
             'filter'=>false,
             'footer'=>'' . $model->getTotal($model->search()->getData(), 'id'),
             'footerHtmlOptions'=>array('class'=>'grid-footer'),
         ),
    ),
));

Get Total

public function getTotal($records,$colName){        
        $total = 0.0;

        if(count($records) > 0){
            foreach ($records as $record) {
                    $total += $record->$colName;
            }
        }
        return number_format($total,2);
    }
  1. Second column value are calculate user fee.

  2. In footer sum of User Fee values get the wrong sum. It gives the sum of user ids. and id is table column name.

  3. How can I get the sum of User fee column values

Upvotes: 2

Views: 3424

Answers (1)

guychouk
guychouk

Reputation: 681

Instead of using a literal representation of id, try using the $data variable created by CGridView, which actually IS the current record from the $model currently being processed in each CGridView iteration.

Your code would then be:

array(
    'name'=>'id',
    'header' => 'User Fee',
    'type' => 'raw',
    'value' => '$data->id',
    'filter' => false,
    'footer' => '$model->getTotal($data)',
    'footerHtmlOptions' => array('class'=>'grid-footer'),
),

Notice the value of the type attribute is set to raw.
You can even use a PHP function and pass it the $data variable, like so:

array(
    'name'=>'id',
    'header' => 'User Fee',
    'type' => 'raw',
    'value' => function ($data) { ... handle $data how you like ... }
    'filter' => false,
    'footer' => '$model->getTotal($data)',
    'footerHtmlOptions' => array('class'=>'grid-footer'),
),

For more information check out special variables in Yii

Upvotes: 0

Related Questions