Monday, March 20, 2017

Yii2 gridview sum of column value

Here is some of the sample code to get the sum of the column values in the footer in the gridview. It was 100% working in the gridview in Yii2.

All you need to change is the values

 [
   'label' => 'cost',
   'attribute' => 'cost',
   'value' => function ($model, $key, $index, $widget) {
                            return $model->cost;
                    },
   'footer' => $cost,
 ],

The above code should be added in the gridview with footer enabled.

'showFooter' =>true,

Here cost the value which need to be totaled, so you need to change according to your needs. You also need to add the below code in the view page.

<?php
$cost = 0;
if (!empty($dataProvider->getModels())) {
 foreach ($dataProvider->getModels() as $key => $val) {
     $cost += $val->cost;
    }
}
?>

Use this code and calculate sum of values in the footer in the Yii2 Gridview.

Thanks for the code to make it easy. For more refere go to techken.in

No comments:

Post a Comment