Yii2 gridview自定义列值

时间:2016-10-12 10:34:23

标签: gridview yii2

我想在列中的交易表中显示一个/所有帐户的总余额。余额列应显示添加前一行总余额的余额。 我的gridview代码是

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

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

我的模型中的代码如下。我可以通过硬编码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;
    }

我想像这样显示结果 enter image description here

我在gridview中尝试了以下代码,但它仅显示了单个行的余额

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

2 个答案:

答案 0 :(得分:5)

在GridView中:

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

型号:

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;
}

答案 1 :(得分:0)

试试这个

git log