Sao Ho
Sao Ho

Reputation: 139

Yii2 gridview custom value

<?php $sums = app\models\Sku3d::find()->select(["DATE_FORMAT(approvedate, '%m-%Y') as c_date", 'sum(totalhours) as total', 'count(sku) as sku'])
                ->where(['status' => 'Approved'])->groupBy('c_date')
                ->createCommand()
                ->queryAll();
    foreach ($sums as $sum){ ?>
<tr>      
<td><?=$sum['c_date'] ?></td>
<td><?=$sum['sku']  ?></td>
<td><?=$sum['total']  ?></td>  
</tr>
  <?php } ?>

I used the code above to count total products and sum total hours in a month. Currently i used table structure to display the data. Can I use yii2 gridview to display the data above?

Thanks.

Upvotes: 0

Views: 1303

Answers (1)

Anton Rybalko
Anton Rybalko

Reputation: 1314

See Data Providers section of Yii2 documentation. You can create Query object and use ActiveDataProvider or place query result to array and use ArrayDataProvider.

<?php 
    $query = (new \yii\db\Query())
        ->select(["DATE_FORMAT(approvedate, '%m-%Y') as c_date", 'sum(totalhours) as total', 'count(sku) as sku'])
        ->from('sku3d')
        ->where(['status' => 'Approved'])
        ->groupBy('c_date');

    $dataProvider = new ActiveDataProvider([
        'query' => $query,
    ]);

    echo GridView::widget([
        'dataProvider' => $dataProvider,
        'columns' => [
            'c_date:text:Month',
            'total:text:Total hours',
            'sku:text:Sku'
        ]
    ]);
?>

Upvotes: 1

Related Questions