I am using Select2 from Yii Booster as dropdown list. I would like to allow user to enter his own value, but I do not know how. I think, there is no configuration for this. I think I might try something like here - Select2 dropdown but allow new values by user? but I do not know how to add this javascript when rendering select2 from php form. Could anyone help? Thank you
Asked
Active
Viewed 864 times
1 Answers
0
I think you can add a javascript function as a option in the widget's options by prefixing it with 'js:', for example:
$this->widget(
'booster.widgets.TbSelect2',
array(
'asDropDownList' => false,
'name' => 'clevertech',
'options' => array(
'tags' => array('clever', 'is', 'better', 'clevertech'),
'placeholder' => 'type clever, or is, or just type!',
'width' => '40%',
'tokenSeparators' => array(',', ' ')
'createSearchChoice' => 'js:function(term, data) {
if ( $(data).filter( function() {
return this.text.localeCompare(term)===0;
}).length===0) {
return {id:term, text:term};
}',
}
)
)
);
For further debugging, if you open TbSelect2.php you can see what it does with the options:
$options = !empty($this->options) ? CJavaScript::encode($this->options) : '';
And if you go to CJavaScript::encode function you can see it does:
if(is_string($value))
{
if(strpos($value,'js:')===0 && $safe===false)
return substr($value,3);
else
return "'".self::quote($value)."'";
}
Note: I've opened CJavaScript::encode of Yii 1 not 2 but might be the same.

Alexandru Trandafir Catalin
- 2,588
- 2
- 31
- 39
-
Thank you for reply. This would probably work, but i am getting error "'createSearchChoice' is not allowed for Select2 when attached to a – kokoseq Dec 29 '14 at 09:37
-
by the way I am using asDropDownList true – kokoseq Dec 29 '14 at 09:43
-
I ran into a similar problem with custom select2 options that did not allow me to use a dropdown, so I have switched to a hidden input, doesn't it work if you set asDropDownList to false? from what I can see in the code it will use a hidden field. – Alexandru Trandafir Catalin Dec 30 '14 at 11:34
-
Yes, it works when you set asDropDownList to false, but I wanted to use it as DropDownList. Never mind, I use it in tagging mode now and it is ok:-) How did you switched to hidden input? – kokoseq Jan 11 '15 at 20:45
-
I was using select2 plugin alone without this extension, so I had just generated a hidden field with a ID and applied select2 to that ID. – Alexandru Trandafir Catalin Jan 12 '15 at 13:30