V
V
Vitaly Khvan2017-07-04 12:21:17
Yii
Vitaly Khvan, 2017-07-04 12:21:17

How to add Total row in GridView Yii2?

In general, there is a GridView from advanced
output like this:

<?php Pjax::begin(); ?>    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],

            'id',
            'date',
            'operator_count',
            'operator_count2',
            'operator_count4',
             'operator_count4',

        ],
    ]); ?>
<?php Pjax::end(); ?></div>

I can't figure out how to add the Total line,

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Pavlenko, 2017-07-04
@xRites

1) the result will have to be calculated by yourself with the help of add. functions. I do it with a helper:

<?php

namespace app\helpers;

class ArraySum
{
    public static function getSum($array)
    {
        $sumArray=[];
        foreach ($array as $k=>$subArray) {
            foreach ($subArray as $id=>$value) {
                $value = floatval($value);
                if(isset($sumArray[$id])) {
                    $sumArray[$id]+=$value;
                } else {
                    $sumArray[$id]=$value;
                }
            }
        }
        return $sumArray;
    }
}

The code helped me well, but maybe you can adapt it (for example, specify which fields to plus or not).
Then I did this. Let's say I have a multidimensional array like 0=>['id'=>2, 'date'=>'2017-05-12', 'operator_count'=>55, 'operator_count2'=>4, ...] , 1=>['id'=>3, 'date'=>'2017-05-13', 'operator_count'=>57, ...]
This array is passed through my class.
If you use ActiveDataProvider, you need to do in the controller
$dataProvider->prepare();
and then
$total_statistic = \app\helpers\ArraySum::getSum($dataProvider->getModels());
We pass $total_statistic to the view, and there we make the following modifications:
1) add 'showFooter'=>
2) we remake all the "columns" by analogy with the first operator_count (add the rest yourself).
<?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'showFooter'=>true,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],

            'id',
            'date',
            'operator_count'=>[
'attribute'=>'operator_count',
'footer' => $total_statistic['operator_count']
],
            'operator_count2',
            'operator_count4',
             'operator_count4',

        ],
    ]); ?>

Little things remain - you need to decorate it with CSS, finish it, check it ...
But I hope you can handle it yourself.
I would be very grateful if they tell me a better option, but I don’t seem to have seen such a built-in functionality in Yii2

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question