Yii2,设置多个值选择2


Yii2, Set multiple Value Select2

我有这样的加载选择2数据:

$data = ArrayHelper::map(ContactGroups::find()->where(['group_status'=>'ACTIVE'])->asArray()->all(),'group_id', 'group_name'); 
echo $form->field($model, 'group_id')->widget(Select2::classname(), [
 'data' => $data,
 'model' => $model,
  'language' => 'en',
  'options' => ['placeholder' => Yii::t('modules','Pilih Kelompok')],
  'pluginOptions' => [
    'allowClear' => true,
    'multiple' => true,
  ],
])->label('Kelompok');

$data变量返回结果:

Array
(
    [1] => Tanpa Kategori
    [3] => Bisnis
    [4] => Kawan
    [5] => Bisnis Kerang
    [6] => Bisnis Selang
    [99] => Keluarga
)

select2 工作正常,但我无法显示选定的值或initial value. 我错过了什么吗?

您在pluginOptions中添加tags属性以进行多项选择,例如......

$data = ArrayHelper::map(ContactGroups::find()->where(['group_status'=>'ACTIVE'])->asArray()->all(),'group_id', 'group_name'); 
foreach($data as $d)
     $row[]=$d;
echo $form->field($model, 'group_id')->widget(Select2::classname(), [
   'language' => 'en',
   'name' => 'group_id[]',
   'options' => ['placeholder' => ''],
   'pluginOptions' => [
        'tags' => $row,
        'allowClear' => true,
        'multiple' => true
    ],
])->label('Kelompok');

您显示演示

尝试这样使用。在更新时,我们需要在 1 个变量中获取已选择的值,在 1 个变量中获取所有值。并将其发送到 Select2。

$query = NewsTags::find()->where(['news_id' => $model->id])->all();        
 $services = array();
 $services_id_list = array();
 foreach ($query as $ds) {
 $tag_id = $ds->tag_id;
 $tag_name = Tags::findOne($tag_id)->tag_name;
 $services[$ds->tag_id] = $tag_name;
 array_push($services_id_list, $ds->tag_id);
 }
 $data= ArrayHelper::map(Tags::find()->where([])->all(),'id','tag_name');
 echo Select2::widget([
 'name' => 'NewsTags[tag_id][]',
 'id' => 'newstags-tag_id',
 'value' => $services_id_list,
 'data' => $data,
 'maintainOrder' => true,
 'options' => [
 'placeholder' => 'Select a Service ...',
 'multiple' => true
 ],
 'pluginOptions' => [
 'tags' => true,
 'maximumInputLength' => 10
 ],
 ]);   

这里 NewsTags[tag_id][] 是模型及其列。 我们在这里不直接调用$model->属性

看看 kartik''base''InputWidget 第 190 行的代码:

if ($this->hasModel()) {
   $this->name = !isset($this->options['name']) ? Html::getInputName($this->model, $this->attribute) : $this->options['name'];
   $this->value = !isset($this->options['value'])? Html::getAttributeValue($this->model, $this->attribute) :                                $this->options['value'];
}

我发现,当使用 AJAX 加载数据时,应该在 options[value] 中设置初始多个值,如下所示:

<?= $form->field($model, $attribute)->widget(Select2::className(), [
'initValueText' => $initText, // array of text to show in the tag for the selected items 
'options' => [
    'placeholder' => 'Any text you want ...',
    'multiple' => true,             
    'class' => 'form-control',
    'value' => $initIds, // array of Id of the selected items
],

而在 initValueText 旁边设置值会导致array_combine错误