Hello,
I would like to know how can I sum an entire column of a Gridview and put the total on the footer. Considering that the values displayed in that column are not stored on DB, but are generated in a function of a related model.
This is how I show the values on the grid:
[
'label' => 'Precio Dosis',
'format' => 'currency',
'value' => 'dosis.preciodosis',
],
The ‘dosis.preciodosis’ is nothing more than this function in the “Dosis” model (basically it multiplies the cost of a product with the amount used):
public function getprecioDosis()
{
return $this->insumo->precio * $this->cantidad;
}
Here’s my view:
You have to prepare footer sum before display GridView, such as:
$total = 0;
foreach($dataProvider->models as $m)
{
$total += $m->dosis->precioDosis;
}
echo GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
[
'header' => 'Precio Dosis',
'value' => function($data) {
return $data->dosis->precioDosis;
},
'footer' => $total
],
],
]);
You have to prepare footer sum before display GridView, such as:
$total = 0;
foreach($dataProvider->models as $m)
{
$total += $m->dosis->precioDosis;
}
echo GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
[
'header' => 'Precio Dosis',
'value' => function($data) {
return $data->dosis->precioDosis;
},
'footer' => $total
],
],
]);
Neat, it works, thank you.
Somehow the sum value lost the currency format, but the sum is OK.
Regards.
Try with:
'footer' => \Yii::$app->formatter->asCurrency($total)
Thank you very much, it’s solved now.