Wednesday 11 June 2014

Display total amount on Yii Grid

In this example we are displaying total amount of two fields in footer. Here we are calling getTotal() method (Defined in Model. See Step 2) by passing three parameters to it. First parameters is $model->search()->getData() which returns the data items currently available, second and third parameters are the values of amount_1 and amount_2 respectively.

Step 1:

<?php
$this->widget('bootstrap.widgets.TbGridView', array(
    'id' => 'my-grid',
    'dataProvider' => $model->search(),
    'template' => '{items}',
    'columns' => array(
        array(
            'header' =>'Amount 1',
            'name' => 'amount_1',
            'footer'=>'Total (Amount 1 + Amount 2)',
        ),        
        array(
            'header' => 'Amount 2',
            'name' => 'amount_2',
            'footer' => $model->getTotal($model->search()->getData(), 'amount_1','amount_2'),
        ),        
    ),
));
?>

Step 2:

<?php
    public function getTotal($records, $data1, $data2) {
        $total = 0;
        foreach ($records as $record) {
            $total += $record->$data1 + $record->$data2;
        }
        return number_format($total, 2);
    }
?>

No comments:

Post a Comment