I have a Select2 auto-complete input (built via SonataAdmin), but cannot for the life of me figure out how to programmatically set it to a known key/value pair.
There's a JS Fiddle here that shows roughly what I have. What I want to know is what function I can attach to the button so that
- the Select2 field shows the text "NEW VALUE" to the user, and
- the Select2 field will submit a value of "1" when the form is sent to the server
I have tried all sorts of combinations of jQuery and Select2 data
and val
methods, called against various inputs on the page, but nothing seems to work... surely there's some way to do this?
-- Edit --
The accepted answer below is very useful, helps shed some light on the right way to initialise the selection and explains what initSelection is for.
Having said that, it seems that my biggest mistake here was the way I was trying to trigger the change.
I was using:
$(element).select2('data', newObject).trigger('change');
But this results in an empty add
object inside select2's change event.
If, instead, you use:
$(element).select2('data', newObject, true);
then the code works as it should, with the newObject
available in select2's change event and the values being set correctly.
I hope this extra information helps somebody else!