masteryoda
masteryoda

Reputation: 282

yii2 select2 widget allow new tags with autocomplete

I use Krajee select2 widget. For now i have this code:

<?php
echo '<label class="control-label">Tag Content</label>';
echo Select2::widget([
    'model' => $model,
    'attribute' => 'tags',
    'name' => 'tags',
    'data' => Tag::getTags(),
    'options' => [
        'placeholder' => 'Select a color ...',
        'class' => 'form-control',
        'multiple' => true,
    ],]);
?>

This is working, but i need also allow users to eneter new tags (not ionly using tags from model). What i need to do to achieve this? Regards

Upvotes: 1

Views: 2843

Answers (1)

arogachev
arogachev

Reputation: 33548

To enable tags mode you need to specify tags option in pluginOptions.

<?= $form->field($model, 'tags')->widget(Select2::classname(), [
    'options' => [
        'placeholder' => 'Select a color ...',
    ],
    'pluginOptions' => [
        'tags' => Tag::getTags(),
    ],
]) ?>

I also removed redundant options (assuming you are using it inside ActiveForm).

You can read more in official extension documentation. There is also an example of preselecting values.

Upvotes: 1

Related Questions