How to define custom lable in gridview filled by ArrayDataProvider?

475 views Asked by At

I'm getting some data using a webservice which is in JSON format and want to dispaly them using gridview. I use ArrayDataProvider to send data to the gridview using this code:

$dataProvider = new ArrayDataProvider([
   'allModels' => $data,
   'pagination' => [
       'pageSize' => 10,
    ],
    'sort' => [
       'attributes' => ['fname', 'lname', 'age', 'email'],
    ],
]);

How can I change label of columns in grid? For example First Name instead of fname?

Thank you.

2

There are 2 answers

0
ScaisEdge On

In gridview you can change the label atribute

  <?= GridView::widget([
      'dataProvider' => $dataProvider,
      'columns' => [
          ['class' => 'yii\grid\SerialColumn'],
          [
              'label' => 'First Name',
              'attribute' => 'fname',
          ],
  ]);

http://www.yiiframework.com/doc-2.0/yii-grid-datacolumn.html

http://www.yiiframework.com/doc-2.0/yii-grid-datacolumn.html#$label-detail

0
hd. On

I found the answer for this url https://github.com/yiisoft/yii2/issues/11490

Add a new property ArrayDataProvider::modelClass to manually specify which model ArrayDataProvider must use to generate column labels. This change will allow ArrayDataProvider to correctly generate column labels using Model::getAttributeLabel() method when provided data array is empty.