我使用这些数据来填充 select2 kartik 组合框,这是我的 yii2 代码,
echo \kartik\widgets\Select2::widget([
'attribute' => 'pembuatSoal_id',
'model' => $model,
'data' => array_merge(["" => ""], \yii\helpers\ArrayHelper::map(\app\models\ViewUsernameGuru::find()->all(), "uname", "nama")),
'options' => ['placeholder' => 'Pilih Guru...', 'id' => 'guru-id', 'class' => "form-control"],
'pluginOptions' => [
'allowClear' => true,
'theme' => \kartik\widgets\Select2::THEME_BOOTSTRAP
],
]);
uname字段作为select2的值,nama作为显示值。但结果是这样的:
但是当uname字段的值为number时,select2会自动随着select2项的数组索引而改变。
希望有人能给我解决方案。
谢谢。
试试这个:
echo \kartik\widgets\Select2::widget([
'attribute' => 'pembuatSoal_id',
'model' => $model,
'data' => \yii\helpers\ArrayHelper::map(\app\models\ViewUsernameGuru::find()->all(), "uname", "nama")),
'options' => ['placeholder' => 'Pilih Guru...', 'id' => 'guru-id', 'class' => "form-control"],
'pluginOptions' => [
'allowClear' => true,
'theme' => \kartik\widgets\Select2::THEME_BOOTSTRAP
],
]);
在这里找到它:
如果删除 array_merge,索引将不会更改。
只需添加此选项即可允许空选择并为其命名。
'filterWidgetOptions'=>[
'pluginOptions' => ['allowClear' => true],
],
'filterInputOptions' => ['placeholder' => \Yii::t('app', 'Any Entry')],
我测试了过滤器上的设置,但普通小部件的设置是相似的:
'options' => ['placeholder' => 'Any entry'],
'pluginOptions' => [
'allowClear' => true
],
非常适合我... 所以就你而言,这只是
echo \kartik\widgets\Select2::widget([
'attribute' => 'pembuatSoal_id',
'model' => $model,
'data' => \yii\helpers\ArrayHelper::map(\app\models\ViewUsernameGuru::find()->all(), "uname", "nama"),
'options' => ['placeholder' => 'Pilih Guru...', 'id' => 'guru-id', 'class' => "form-control"],
'pluginOptions' => [
'allowClear' => true,
'theme' => \kartik\widgets\Select2::THEME_BOOTSTRAP
],
]);
array_merge
,它重新索引了数字数组,数字字符串,在这种情况下,以下结果相同
[9 => 'foo']
['9' => 'foo']
我相信所需的功能是具有“正常”选择标签的外观,能够选择“空”第一个选项,该选项在选择时设置空值。
我不断搜索并找到了简单的解决方案,即添加数组
['' => 'Select value...'] + [0 => false, 1 => true]
如果第一个选项元素为空,则设置不应包含
placeholder
,因为它不会将其显示在选项列表中,而是将其用作选项名称。
allowClear
可以设置为 false,或者将其保留为默认状态导致:
echo \kartik\widgets\Select2::widget([
'attribute' => 'pembuatSoal_id',
'model' => $model,
'data' => (["" => "Pilih Guru..."] + \yii\helpers\ArrayHelper::map(\app\models\ViewUsernameGuru::find()->all(), "uname", "nama")),
'options' => ['id' => 'guru-id', 'class' => "form-control"],
'pluginOptions' => [
'allowClear' => false, // false is default so could be left out
'theme' => \kartik\widgets\Select2::THEME_BOOTSTRAP,
'dropdownAutoWidth' => 'true', // to autocalculate width of selection list
],
]);
来源: