A
A
Abr_ya2019-08-17 14:23:20
Yii
Abr_ya, 2019-08-17 14:23:20

Yii2, Grid view, Label - how to make a label from several fields by foreign key?

The example is rather trivial.
I have two tables. I display services, they have a user id. Instead of id, I want to display the last name and first name, which are stored in the users table.
I follow this instruction:
php-lessons.com/blog/2016/06/06/yii2-view-data-ral...
created a function in the service model:

// получаем пользователя по ID
    public function getUser() {
        return ($this->hasOne(UserRecord::className(), ['id' => 'user_id']));
    }

In the view that is responsible for the output of services, when calling the widget, I specify:
...
array('attribute'=>'user_id','filter'=>$users,'label'=>'User','value'=>('user.last_name')),
...

And everything is fine, but this is only a surname.
And how can I display user.first_name and user.last_name in this column separated by a space?!
Everything that came to my mind, falls with errors! (

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim, 2019-08-17
@Abr_ya

You need to create a new method in the User model:
Alternatively, create an anonymous function in the view:

public function getFullName(string $separator = ' '): string
{
    return implode($separator, array_filter([
        $this->firstName,
        $this->middleName,
        $this->lastName
    ]));
}

'value'=> function($model) {
return $model->first_name .' '. $model->last_name
}

Use:
user.fullName
//или

$user->getFullName(', ')

V
Viktor Yanyshev, 2019-08-17
@villiwalla

value => function (value) { return value->user->lastName .’ ‘.  value->user->firstName;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question