0

I am using a Select2 widget for Yii2. It shows a list with the ids of the users.

I need to show two fields defined in my model called Users: first_name_user and last_name_user. Like this:

Daniel Gates
John Connor
John Doe
Maria Key

But I don't know how use map() to show more than one field.

<?= $form
    ->field($model, 'id_user')
    ->widget(\common\widgets\Select2::classname(), [
        'items' => \yii\helpers\ArrayHelper::map(\app\models\Users::find()->orderBy('name_user')->all(), 'id_user', 'name_user')
    ])
?>
Roby Sottini
  • 2,117
  • 6
  • 48
  • 88

2 Answers2

4

Model

Add use app\models\Users; and use yii\helpers\ArrayHelper; at top.

public function userList()
{
    $userList  = [];
    $users = Users::find()->orderBy('first_name_user')->all();

    $userList = ArrayHelper::map($users, 'id_user', function ($user) {
       return $user->first_name_user.' '.$user->last_name_user;
    });

    return $userList;
}

_form

<?= $form->field($model, 'id_user')->widget(Select2::className(), [
    'data' => $model->userList(),
    'options' => ['placeholder' => 'Select User'],
]) ?>
Insane Skull
  • 9,220
  • 9
  • 44
  • 63
1
  1. You need to use data option instead of items for Select2.

  2. You need to modify your query to show the concatenated first_name_user and last_name_user as an alias and then return it along with the id column to be used in Select2 by ArrayHelper::map().

It's better to add a function to the model you are using to populate the form and return the results from there to the ArrayHelper::map(). Your query should look like

function userList(){
return \app\models\Users::find()
       ->select([new \yii\db\Expression('[[id_user]],CONCAT([[first_name_user]]," ",[[last_name_user]]) as full_user_name')])
       ->orderBy('name_user')
       ->all();
}

Your form field should look like below

<?=
$form->field($model, 'id_user')->widget(Select2::className(), [
    'data' => \yii\helpers\ArrayHelper::map($model->userList(), 'id_user', 'full_user_name'),
    'options' => [
        'placeholder' => 'Select User',
        'id' => 'id_user'
    ],
    'theme' => Select2::THEME_DEFAULT,
    'pluginOptions' => [
        'allowClear' => true
    ],
]);
?>
Muhammad Omer Aslam
  • 22,976
  • 9
  • 42
  • 68