M
M
Mark2019-06-08 12:05:26
Yii
Mark, 2019-06-08 12:05:26

How to make a total sum in GridView Yii2 taking into account filters?

It is necessary in the footer of the GridView to display the sum of the values ​​of certain columns in the format:
Sum of the values ​​of the columns in the GridView/Total sum of values.

Example

У нас есть столбец "Просмотры". Всего 5 записей, суммарно их кол-во просмотров - 1000.
В GridView 2 записи, в сумме у них просмотров - 200.
На выходе имеем:
200/1000

Sum of column values ​​in GridView - implemented.
Implementation

Класс:
class NumberColumn extends DataColumn
{
    private $total = 0;

    public function getDataCellValue($model, $key, $index)
    {
        $value = parent::getDataCellValue($model, $key, $index);
        $this->total += $value;
        return $value;
    }

    protected function renderFooterCellContent()
    {
        return $this->grid->formatter->format($this->total, $this->format);
    }
}

Ячейка в columns GV:
[
                'class' => \app\components\NumberColumn::class,
                'attribute' => 'views',
            ],


It remains to display the total sum of the values, but so that the filters are applicable .
Example

У нас два столбца "Views" и "Country".
Записи:
1. V: 100, Country: RU.
2. V: 100, Country: RU.
3. V: 100, Country: RU.
4. V: 200, Country: USA.
В GridView, 2 записи(1, 2), включен фильтр Country=RU.
Итоговое число: 200/300.
Если бы фильтр не был бы включен, итог был бы: 200/500.

How can this be achieved? In fact, it is necessary to somehow pick up the filters of the searchModel, or carry out a calculation in it.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question