Search code examples
phpyiijquery-select2yii-extensionsyii2

yii2-widget, Select2 and taggest support


Can i use taggest support with dats only from model? i don't need new tags creating by user

echo '<label class="control-label">Tag Content</label>';
echo Select2::widget([
'name' => 'color_1', 
'options' => ['placeholder' => 'Select a color ...', 'class'=>'form-control'],
'pluginOptions' => [
    'tags' => ["red", "green", "blue", "orange", "white", "black", "purple", "cyan",            "teal"],
    'maximumInputLength' => 10
],

]);

Now user can add tags like "gr","r" and other, but i don't want it. I only need tags creating by my model (like stackoverflow)


Solution

  • in your _form.php

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

    then add following code in your model

    public static function getOptions(){
        $data=  static::find()->all();
       $value=(count($data)==0)? [''=>'']: \yii\helpers\ArrayHelper::map($data, 'id','name'); //id = your ID model, name = your caption
    
        return $value;
    }