Home » BLOG » Yii2.0 framework » How to add the summary in the Gridview footer in Yii2

How to add the summary in the Gridview footer in Yii2

category:  Yii2.0 framework

Currently, I am building the invoice feature in my own application with Yii2. I use the gridview widget for displaying all invoices data. I want to add the grand total for all invoices. Just like the screenshot below.

gridview sum

To do that, I have to add the extra code in two places.

Note that, I generate the CRUD from Gii. So I will show only the code that I add for displaying the grand total at the gridview footer.

First place, I add the grand total column in the gridview footer and enable the “showFooter” option.

Invoice View:

<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,   
    'showFooter' => true, // show footer section of the gridview widget
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],
            [// total,
                'attribute' => 'total',
                'value' => function($data) {
                    // show the amount in money format => 50,000.00
                    return number_format($data['total'], 2);
                'filter' => false, //disable the filter for this field
                // I create the summary function in my Invoice model
                'footer' => Invoice::getTotal($dataProvider->models, 'total'),

Second place, I add the summary function in the model. So this function can sum up the total for me.

Invoice model:

public static function getTotal($provider, $fieldName)
    $total = 0;

    foreach ($provider as $item) {
        $total += $item[$fieldName];

    // add number_format() before return
    $total = number_format( $total, 2 );

    return $total;

And that’s it. The grand total column at the footer will summarize the total column of each invoice on each page in gridview widget.