Yii2 - 如何在GridView中对我的列进行求和?

时间:2017-07-17 13:03:19

标签: gridview yii2 sum

如何在GridView中汇总列的值并显示总数?

我的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 个答案:

答案 0 :(得分:1)

更好更有活力的方式:

1)在模型中创建函数

public static function getTotal($provider, $columnName)
{
    $total = 0;
    foreach ($provider as $item) {
      $total += $item[$columnName];
  }
  return $total;  
}

2)查看

<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'showFooter' => true,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],
        'account_code',
        'account_name',
        [
         'attribute' =>'amount',
         'footer' => ModelName::getTotal($dataProvider->models, 'amount'),
        ],

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

答案 1 :(得分:0)

您可以添加一些代码来计算总数

这种操作应该在您的控制器中完成(或者您可以在模型中添加适当的功能)

在你的情况下,你是直接在视野中工作(这不是一个好习惯,但无论如何)哟

  $dataProvider = new ActiveDataProvider([
  'query' => Accounts::find()->where('account_type=1'),
  'sort'=> ['defaultOrder' => ['account_code'=>SORT_ASC]],
  ]);

   // calculate the result in $mySum
   foreach ($provider as $item) {
          $mySum += $item['amount'];

      }

  // add showfooter => true,
  echo GridView::widget([
    'dataProvider' => $dataProvider,
    'showFooter' => true,
    'columns' => [
          ['class' => 'yii\grid\SerialColumn'],
          'account_code',
          'account_name',
          [
           'attribute' =>'amount',
           'footer' => $mySum, // add the footer values
          ],
          ['class' => 'yii\grid\ActionColumn'],
  ],
  ......

答案 2 :(得分:-1)

要计算所有页面的数量,请对代码进行一些更改:

$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'],
    ] 
]);