How to add the summary in the Gridview footer in Yii2
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

Updated:   Yii2.0 framework 1 min read

Your support helps keep this blog running! Secure payments via Paypal and Stripe.


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.

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:

<?php
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.


Your support helps keep this blog running! Secure payments via Paypal and Stripe.


Senior WordPress & WooCommerce Developer

Senior WordPress & WooCommerce Developer

I’m a professional WordPress and WooCommerce developer based in Chiang Mai, Thailand, with over a decade of experience creating fast, secure, and scalable websites. From custom themes and plugins to full WooCommerce stores, I help businesses build a strong and reliable online presence. Need a developer you can count on? View my portfolio or get in touch to discuss your project.