Avinash
Avinash

Reputation: 72

How to create custom column in Yii2 grid view by using other table value

Suppose I have table A and B.

Table A contain column id, name

id  | name  
----|-----------
1   |   X
2   |   Y   
3   |   Z  

Table B contain column id, tax_type, rate

id  | tax_type  | rate
----|-----------|--------
1   |   services|12
2   |   vat     |3
3   |   others  |4

I have created grid view using table B, so the column of grid view are id and name.

But I want column dynamically in grid view by fetching table B values.

Like:

 id | name  |services   | vat   | others
----|-------|-----------|-------|--------
1   |   X   |  12       |  3    |   4
2   |   Y   |  12       |  3    |   4
3   |   Z   |  12       |  3    |   4

If the row change in table B then columns are also change in grid view.

Upvotes: 0

Views: 5207

Answers (1)

Beowulfenator
Beowulfenator

Reputation: 2300

Your Gridview columns can have any value. Do the following in your view:

First, get your data from table B:

$taxInfo = TableB::find()->indexBy('tax_type')->all();

Then, in your view in column definitions just add this:

'columns' => [
    'id',
    'name',

    //...

    [
        'label' => 'Services',
        'value' => function ($model) use $taxInfo {
            $taxInfoObject = $taxInfo['services'];
            return $taxInfoObject->rate;
        }
    ],
    [
        'label' => 'VAT',
        'value' => function ($model) use $taxInfo {
            $taxInfoObject = $taxInfo['vat'];
            return $taxInfoObject->rate;
        }
    ],
    [
        'label' => 'Others',
        'value' => function ($model) use $taxInfo {
            $taxInfoObject = $taxInfo['others'];
            return $taxInfoObject->rate;
        }
    ],
]

Note how the $taxInfo variable we defined above is passed to our anonymous functions. (Generally those functions work with $model which, in your case, would contain a specific row of table A).

Upvotes: 1

Related Questions