title: Creating a 'Ajaxified' Form Field Type
body: <p>In my application I've got a couple of form fields with many options. The problem I experienced is similar to <a href="https://stackoverflow.com/questions/26469536/symfony2-how-to-create-a-form-field-of-type-entity-without-values">this question</a>: getting and parsing all options at every page load is expensive (Twig renders all options over and over again while no client side caching possible). That problem made me create a way to send the options via AJAX to the browser. Fairly simple approach:</p>
  
  <ol>
  <li>Get all options (key-value) via AJAX (for example by getting /countries.json) and cache if possible. (in this case it's not very likely country names change very often)</li>
  <li>Use selectize, select2 or a similar plugin to insert the options into the DOM.</li>
  <li>Enjoy a faster Form :-)</li>
  </ol>
  
  <p>To prevent Symfony from querying all options (not necessary: they're loading via AJAX) I added <code>setMaxResults(0)</code> to the <code>QueryBuilder</code> when the form is loaded (by adding an option via the controller). Yes, that's kludge. When submitting a form it will still perform a query, because it has to verify if the selected option exists (and check for Constraints).</p>
  
  <p>I would like to create a <a href="http://symfony.com/doc/current/cookbook/form/create_custom_field_type.html" rel="nofollow noreferrer">custom Form Field Type</a> that adds this functionality to the current <code>EntityType</code>: don't load the options while rendering the form, but still check if the selected option exists. I found <a href="https://stackoverflow.com/questions/13321771/symfony2-change-choices-with-ajax-and-validation">many</a> <a href="http://showmethecode.es/php/symfony/symfony2-4-dependent-forms/" rel="nofollow noreferrer">examples</a> related to <a href="http://symfony.com/doc/current/cookbook/form/dynamic_form_modification.html" rel="nofollow noreferrer">dynamically modifying a form</a>, but I haven't found examples related to modifying just one form field, independently of it's parent form.</p>
  
  <p>How do I create a form field type like this? What's a good starting point? Extend <code>EntityType</code>, <code>ChoiceType</code> or an other approach? </p>
  
  <p>I'm already using Symfony 3.1, so using <a href="http://symfony.com/blog/new-in-symfony-3-2-lazy-loading-of-form-choices" rel="nofollow noreferrer">lazy loading of form choices</a> (New in Symfony 3.2) won't be a problem. Not sure if this new feature is related to my problem.</p>