Yii2: Display data from Sql which has same value into one column in Kartik gridview

1k views Asked by At

I'm trying to develop system using Yii2 framework. I've data in my database, and I want to display all the data from products table. For example:

Products Table

---------------------------------------------------------------------
**id** | **product** | **color**   | **quantity**   |    **size**   |
  
  1    |    t-shirt  |     red     |       2        |     L         | 
  2    |    t-shirt  |     blue    |       3        |     M         |
  3    |    pants    |     black   |       6        |     M         |

and I want to display this data to kartik gridview in index.php. But I want to display data by product not id, so my expected result is like this my index.php

Expected Result

product   |   quantity    |   
  
 t-shirt  |      5        |   
 pants    |      6        | 

My expected result avoid, color and size. It's merge all same product into one column in gridview.

How I can get like that? This is my code in index.php:

  <?php
   use kartik\grid\GridView;

  <?= GridView::widget([
    'dataProvider' => $dataProvider,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn',
            'header' => 'No',
        ],
        [
            'label' => 'product',
            'value' => function($data) {
               return $data->product;
            }
        ],

        [
            'label' => 'quantity',
            'value' => function($data) {
               return $data->quantity;
            }
        ],
        ['class' => 'yii\grid\ActionColumn'],
    ],
    'toolbar' => [
        ['content' =>
            Html::a('<i class="glyphicon glyphicon-repeat"></i>', ['index'], ['data-pjax' => false, 'class' => 'btn btn-default', 'title' => 'Reset Grid'])
        ],
        '{export}',
        '{toggleData}'
    ],
    'panel' => [
        'heading' => '<i class="glyphicon glyphicon-align-left"></i>&nbsp;&nbsp;<b>Products List</b>',
        'before' => '', //IMPORTANT
    ],
]);
?>

and if I use above code, I got result like this:

    product   |   quantity    |   
      
     t-shirt  |      2        |
     t-shirt  |      3        |     
     pants    |      6        | 

Any help would be appreciated. Thanks

1

There are 1 answers

3
zakrzu On

Use: http://www.yiiframework.com/doc-2.0/yii-data-sqldataprovider.html

And in sql use group by, count ect...

Then in GridView columns use like that:

[
    'label' => 'product',
    'value' => function($data) {
        return $data['product'];
    },
],