title: Programmatically set the value of a Select2 ajax
body: <p>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.</p>
  
  <p>There's <a href="http://jsfiddle.net/caponica/xjo4eguz/1/" rel="noreferrer">a JS Fiddle here</a> that shows roughly what I have. What I want to know is what function I can attach to the button so that</p>
  
  <ul>
  <li>the Select2 field shows the text "NEW VALUE" to the user, and</li>
  <li>the Select2 field will submit a value of "1" when the form is sent to the server</li>
  </ul>
  
  <p>I have tried all sorts of combinations of jQuery and Select2 <code>data</code> and <code>val</code> methods, called against various inputs on the page, but nothing seems to work... surely there's some way to do this?</p>
  
  <p>-- Edit --</p>
  
  <p>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.</p>
  
  <p>Having said that, it seems that my biggest mistake here was the way I was trying to trigger the change.</p>
  
  <p>I was using:</p>
  
  <pre><code>$(element).select2('data', newObject).trigger('change');
  </code></pre>
  
  <p>But this results in an empty <code>add</code> object inside select2's change event.</p>
  
  <p>If, instead, you use:</p>
  
  <pre><code>$(element).select2('data', newObject, true);
  </code></pre>
  
  <p>then the code works as it should, with the <code>newObject</code> available in select2's change event and the values being set correctly.</p>
  
  <p>I hope this extra information helps somebody else!</p>