Yii2 - How to make a sum of my column in GridView?

Viewed 4506

How do I sum up the values of a column in my GridView and display the total?

My GridView:

$dataProvider = new ActiveDataProvider([
'query' => Accounts::find()->where('account_type=1'),
'sort'=> ['defaultOrder' => ['account_code'=>SORT_ASC]],
]);
echo GridView::widget([
'dataProvider' => $dataProvider,
        'columns' => [
        ['class' => 'yii\grid\SerialColumn'],
        'account_code',
        'account_name',
        'amount',
        ['class' => 'yii\grid\ActionColumn'],
        ],

My table:

3 Answers

To calculate the amount for all pages, make some changes to your code:

$dataProvider = new ActiveDataProvider([
    'query' => Accounts::find()->where('account_type=1'),
    'sort'=> ['defaultOrder' => ['account_code'=>SORT_ASC]],
]);
echo GridView::widget([
    'dataProvider' => $dataProvider,
    'showFooter' => true,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],

        'account_code',
        'account_name',
        [
            'attribute' =>'amount',
            'footer' => $dataProvider->query->sum('amount'),
        ],

        ['class' => 'yii\grid\ActionColumn'],
    ] 
]);
Related