-1

I have model Blog and i have relation there:

public function getRelUser()
    {
        return $this->hasOne(UrUser::className(), ['Id' => 'Rel_User']);
    }

An i want to use fullName in my index of blogView in gridView:

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

            'Id',
            'Title',
            'Description',
            'Rel_User',
            [
        'attribute' => 'Rel_User',
        'value' => 'relUser.Name'
        ], 
            'CreatedAt',
            // 'IsDeleted',

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

This return me only name in column. I want to return full name.

qwerty
  • 101
  • 1
  • 10

2 Answers2

5

Add new method in the UrUser model:

class UrUser extends \yii\db\ActiveRecord
{
    ....

    public function getFullName()
    {
        return $this->name .' '. $this->last_name;
    }
}

and use it in your view like this:

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

            'Id',
            'Title',
            'Description',
            'Rel_User',
            [
                'attribute' => 'Rel_User',
                'value' => function ($model) {
                    return $model->relUser->getFullName();
                },
             ], 
            'CreatedAt',
            // 'IsDeleted',

            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>
Andrew Bu
  • 201
  • 2
  • 5
  • 2
    I think you don't need the anonymous function. `'value' => relUser.fullName` may be enough as you already defined a getter method for it. – Salem Ouerdani Mar 04 '16 at 11:57
  • when i used to:`'value' => 'relUser.fullName'` it display me 'not set' value – qwerty Mar 04 '16 at 12:08
4

Try this

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

            'Id',
            'Title',
            'Description',
            'Rel_User',
            [
        'attribute' => 'Rel_User',
        'value' => function($model) { 
              return $model->relUser->name  . " " . $model->relUser->last_name ;
            },
        ], 
            'CreatedAt',
            // 'IsDeleted',

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

UPDATE for CDetailView. This should work

[
  'label'=>'Full Name',
  'value'=>'$data->relUser->name . " " . $data->relUser->last_name',
]
Nabin Kunwar
  • 1,965
  • 14
  • 29