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')
    ])
?>
4

2 回答 2

4

模型

在顶部添加use app\models\Users;和。use yii\helpers\ArrayHelper;

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->field($model, 'id_user')->widget(Select2::className(), [
    'data' => $model->userList(),
    'options' => ['placeholder' => 'Select User'],
]) ?>
于 2018-01-26T05:45:38.410 回答
1
  1. 您需要使用dataoption 而不是itemsfor Select2

  2. 您需要修改您的query以显示连接的first_name_userlast_name_user作为别名,然后将其与要在byid中使用的列一起返回。Select2ArrayHelper::map()

最好向您用来填充表单的模型添加一个函数并将结果从那里返回到ArrayHelper::map(). 您的查询应如下所示

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();
}

您的表单字段应如下所示

<?=
$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
    ],
]);
?>
于 2018-01-25T19:23:33.160 回答