Dulf
Dulf

Reputation: 13

Yii2 display the lastname and firstname into select2 widget

I used select2 widget for Yii2. I tried to display the lastname and firstname in the dropdown, but it didn't work.

However, it worked when I only put lastname or firstname. How can I display the two using select2 widget in Yii2?

Here is the code which only runs for one attribute:

<?= $form->field($model, 'user_id')->widget(Select2::classname(), [
    'data' => ArrayHelper::map(User::find()->all(),'id','first_name'),
    'language' => 'en',
    'options' => ['placeholder' => 'Select User'],
    'pluginOptions' => [ 'allowClear' => true ]
]); ?>

I want to display in dropdown a complete name, for example:

Ping lacson

Erap Strada

Upvotes: 0

Views: 308

Answers (1)

Ziki
Ziki

Reputation: 1440

ArrayHelper::map() method can get a callable for 2nd & 3rd arguments. Just use it like this:

'data' => ArrayHelper::map(User::find()->all(), 'id', function (User $model) {
    return "{$model->first_name} {$model->last_name}";
}),

Upvotes: 3

Related Questions