<?=
$form->field($model, 'contributors')->widget(Select2::classname(), [
'initValueText' => '',
'options' => ['placeholder' => 'Search for a Contributor ...'],
'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');
?>
如何显示所选值,现在它将id显示为已选择。 请任何人帮助我。
答案 0 :(得分:3)
<强>更新
很抱歉,迟到的回复没有注意到您需要为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
对的数组形式的选项。
查看您的代码,您希望针对数据库表中的name
显示参与者id
,因此您应该使用ArrayHelper:map()
以及查询Contributors
模型,请参阅下文并更新Contributors
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');
?>