How to add grand total to the bottom of yii2 grid view

I have a grid view which is like this. The columns are calculated with the help of MySQL query and displayed accordingly.


  $subquery = Adanalytics::find()->

            select('id,ad_id,date_event,max(cpc) cpclick,max(cpv) cpview,max(impression) impression,max(view) view,max(clicks) clicks,visitor_ip,publisher_id')->


            where(['publisher_id' =>  Yii::$app->user->identity->id ])->



        select('ad_id,date_event,sum(cpclick) total_click_cost,sum(cpview) total_view_cost,sum(impression) total_impression,sum(view) total_views,sum(clicks) total_clicks,publisher_id')->




    <?= GridView::widget([

    'dataProvider'=>new ActiveDataProvider([

      'query' => $query,


    'filterModel' => $searchModel,

    'columns' => [

        ['class' => 'yii\grid\SerialColumn'],








        ['class' => 'yii\grid\ActionColumn'],


]); ?>

I want to show a grand total column at the bottom of this grid view.

For example.


        'grand_total_views', //This is the sum of all displayed views

        'grand_total_clicks',//This is the sum of all displayed clicks

        'grand_total_click_cost',//THis is the sum of all displayed cost

        'grand_total_view_cost',//This is the sum of all displayed view cost

To do that I have code in my controller which is like this.

public function actionIndex()


        $searchModel = new Adanalytics2Search();

        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        $grandTotal = [];

        foreach ($dataProvider->getModels() as  $value) {

          // var_dump($value);

          // exit();

            $grandTotal['total_click_cost'] += $value['total_click_cost'];

            $grandTotal['total_view_cost'] += $value['total_view_cost'];



         return $this->render('index', [

             'searchModel' => $searchModel,

             'dataProvider' => $dataProvider,

             'grandTotal'  => $grandTotal,



But it is producing the error in at this way.

Undefined index: total_click_cost

Where am I going wrong? Or is there any other way to solve this problem?

I guess you’d need to set initial values to grandTotal array members elements before incrementing them.

Can you show me an example for the same?

I got the answer here