Fadly Dzil
Fadly Dzil

Reputation: 2206

merge on column based relational table in gridview yii2

in index.php :

'columns' => [
     ['class' => 'yii\grid\SerialColumn'],
       'ID_REQUEST',
       'NOMOR_SURAT',
       [
          'label' => 'Nama Depan',    
          'attribute' => 'ID_KARYAWAN',
          'value' => 'iDKARYAWAN.FIRST_NAME'
       ],
       [
          'label' => 'Nama Belakang',
          'attribute' => 'ID_KARYAWAN',
          'value' => 'iDKARYAWAN.LAST_NAME'
       ],

which is iDKARYAWAN is relation from another table in my model

class Request extends \yii\db\ActiveRecord {

/**
 * @inheritdoc
 */
public static function tableName() {
    return 'ytms_it.request';
}

 public function getIDKARYAWAN() {
    return $this->hasOne(Karyawan::className(), ['ID_KARYAWAN' => 'ID_KARYAWAN'])->from(Karyawan::tableName(). ' b');
}

How to merge those two column ?

For the elp, thanks.

Upvotes: 1

Views: 297

Answers (1)

arogachev
arogachev

Reputation: 33538

Create method called getFullName() in related model and calculate full name using PHP concatenation:

use yii\helpers\Html;

...

/**
 * @return string
 */
public function getFullName()
{
    return Html::encode($this->name . ' ' . $this->surname);
}

Optionally define a label for it in attributeLabels() method of related model:

`fullName` => 'Label for full name',

Then in GridView it's possible to display full name of related model in one column like so:

1) The shortest form:

'relatedModel.fullName',

2) Overriding the label:

[
    'attribute' => 'relatedModel.fullName',
    'label' => 'Overrided label',
],

3) Using closure:

[
    'attribute' => 'relatedModel.fullName', // The attribute name can be different in this case
    'value' => function ($model) {
        // You can calculate full name here.
        // But it's better to just call according method since view is only for display.
        return $model->author->fullName; 
    },
],

Another way is to calculate full name using SQL and include as a part of query result in separate column.

Use Active Record - Selecting extra fields official docs section as a guide, also see this related issue on Github - JoinWith - assign a column aliases to an attribute of related model.

Add $fullName as public property of related model class. Modify query like so:

use yii\db\Expression;

...

->joinWith(['relatedModel' => function (\yii\db\ActiveQuery $query) {
    $query->addSelect('fullName' => new Expression("CONCAT(name, ' ', surname)")]);
}]

Then to display it in GridView column you can use one of the options desribed above, for example:

'relatedModel.fullName'

Upvotes: 1

Related Questions