Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 gridview custom column value

Tags:

gridview

yii2

I want to display the total balance of a/all account from my transaction table in a column. The balance column should display the balance adding the previous row total balance. My gridview code is

<?php
     $gridColumns = [
        ['class' => 'yii\grid\SerialColumn'],
                        'account_no',
                        'credit',
                        'debit',
                        [
                            'label' => 'Balance',

                            'value' => function ($model) {
                                return $model::Balance();
                            }
                        ],
                        'created_date:date',
     ];
?>

and the code in my model is given below. I can get the first row value by hardcoding Deptransaction::findOne(1).

public static function Balance()
    {

            $data = DepTransaction::find();

                if($data->credit != 0){ 
         $cap_bal = $cap_bal +($data->credit - $data->debit);            
                }

                if($data->debit != 0){  
                    $int_bal = $int_bal + ($data->credit - $data->debit);  

                }
            $total = $cap_bal+$int_bal;

        return $total;
    }

I want to display the result like this enter image description here

I tried the below code in my gridview but it display balance for the individual row only

'value' => function($data) {
                                if($data['head_type']=="CAP"){ 
                                    $cap_bal = $cap_bal +($data['credit']-$data['debit']);           
                                }

                                if($data['head_type']=="INT"){  
                                    $int_bal = $int_bal+($data['credit']-$data['debit']);  
                                }
                                $total = $total + $cap_bal+$int_bal;
                                return $total;
                            },
like image 982
gojiraki Avatar asked Oct 12 '16 10:10

gojiraki


1 Answers

In GridView:

<?php
 $gridColumns = [
    ['class' => 'yii\grid\SerialColumn'],
    'account_no',
    'credit',
    'debit',
    [
       'label' => 'Balance',
       'value' => function ($model) {
           return $model->Balance();
       }
     ],
     'created_date:date',
 ];
?>

Model:

public function Balance()
{

    $data = DepTransaction::findOne($this->id);

    if($data->credit != 0){ 
       $cap_bal = $cap_bal +($data->credit - $data->debit);            
    }

    if($data->debit != 0){  
       $int_bal = $int_bal + ($data->credit - $data->debit);  
    }

    $total = $cap_bal+$int_bal;

    return $total;
}
like image 57
vishuB Avatar answered Dec 25 '22 10:12

vishuB