更新
抱歉,回复晚了没有注意到您需要为 select2 设置初始文本,因为您正在使用 ajax 选项,因此您应该使用选项initValueText。根据文档
initValueText : 在 Select2 小部件中显示的文本
初始值。这在您使用
带有 ajax 加载数据的小部件和/或您没有提供数据。
查看 ajax 使用部分以获取示例。
所以你需要像下面这样使用它,在你的控制器动作中添加这一行并将它传递给视图,或者在 select2 之前添加它到视图中
$contributorName = empty($model->contributors) ? '' : Contributors::findOne($model->contributors)->name;
<?=
$form->field($model, 'contributors')->widget(Select2::classname(), [
'initValueText' => $contributorName, // set the initial display text
'options' => ['placeholder' => 'Search for a Contributor ...'],
'data'=>yii\helpers\ArrayHelper::map(Contributors::find()->all(),'id','name')
'pluginOptions' => [
'allowClear' => true,
'minimumInputLength' => 3,
'ajax' => [
'url' => \yii\helpers\Url::to(['data2']),
'dataType' => 'json',
'data' => new JsExpression('function(params) { return {q:params.term}; }')
],
'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
'templateResult' => new JsExpression('function(contributor_id) { return contributor_id.text; }'),
'templateSelection' => new JsExpression('function (contributor_id) { return contributor_id.text; }'),
],
])->label('Contributors');
?>
您需要为将显示所选值的值集提供数据选项您希望显示text 而不是id,请以数组形式提供data 选项与key=>value 对。
查看您的代码,您希望在数据库表中针对id 显示贡献者name,因此您应该使用ArrayHelper:map() 以及查询您的Contributors 模型,请参见下文并更新您的字段名称为@ 987654335@ArrayHelper::map()内的模型/表
<?=
$form->field($model, 'contributors')->widget(Select2::classname(), [
'options' => ['placeholder' => 'Search for a Contributor ...'],
'data'=>yii\helpers\ArrayHelper::map(Contributors::find()->all(),'id','name')
'pluginOptions' => [
'allowClear' => true,
'minimumInputLength' => 3,
'ajax' => [
'url' => \yii\helpers\Url::to(['data2']),
'dataType' => 'json',
'data' => new JsExpression('function(params) { return {q:params.term}; }')
],
'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
'templateResult' => new JsExpression('function(contributor_id) { return contributor_id.text; }'),
'templateSelection' => new JsExpression('function (contributor_id) { return contributor_id.text; }'),
],
])->label('Contributors');
?>