HELPME
HELPME

Reputation: 754

How to display names instead of id's in GridView Yii2?

I have a question here. I set the relations between item and sale tables and now my GridView column of Item name is displaying id's of it. But what I need is that it would display Item names instead of ID's. How should I do that?

Here is my GridView column:

[
     'attribute' => 'item_id',
      'value' => 
],

I was thinking that I should write a function with if statement, but I have a lot of names and it would be very long. Is there an easier way to solve it?

Upvotes: 2

Views: 2783

Answers (2)

Sanju Kaniyamattam
Sanju Kaniyamattam

Reputation: 505

In my case it is company table and products table. comp_id is is the primary key in the company table and it has related with products table.

<?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],

            'prod_id',
            'name',
            'description:ntext',
            [
                'attribute' => 'comp_id',
                'value'     => 'comp.name' //getComp()
            ],

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

//getcomp function the product model page.
 public function getComp()
    {`enter code here`
        return $this->hasOne(Company::className(), ['comp_id' => 'comp_id']);
    }

Upvotes: 2

gmc
gmc

Reputation: 3990

Assuming your relationship is called getItems(), and the field for the item's name is called name:

[
     'attribute' => 'items.name'
],

Upvotes: 2

Related Questions