title: Symfony2: Change choices with ajax and validation
body: <p>Scenario: I have a form with 2 selects. When user selects something from the first select, the second select gets populated with new values. This part works fine.</p>
  
  <p>But the form does not get validated since it contains some choices that are not allowed in the initial form.</p>
  
  <p>Form:</p>
  
  <pre><code>&lt;?php
  
  class MyType extends AbstractType
  {
      private $category;
  
      public function __construct($category = null)
      {
          $this-&gt;category = $category;
      }
  
      public function buildForm(FormBuilderInterface $builder, array $options)
      {
          $builder-&gt;add('category', 'choice', array(
              'choices' =&gt; array(
                  'foo' =&gt; 'foo',
                  'bar' =&gt; 'bar'
              )
          );
  
          $builder-&gt;add('template', 'choice', array(
              'choices' =&gt; $this-&gt;loadChoices()
          );
      }
  
      private function loadChoices()
      {
          // load them from DB depending on the $this-&gt;category
      }
  }
  </code></pre>
  
  <p>Initially the category is <code>foo</code>. So the templates for foo get loaded and set as choices. But if the user selects <code>bar</code>, the bar templates get loaded. But the form still has the foo choices and does not validate.</p>
  
  <p>What is the best way to solve this?</p>
  
  <p>One way I found was to just reinitiate the form in the controller:</p>
  
  <pre><code>&lt;?php
  
  $form = $this-&gt;createForm(new MyType());
  
  if ($request-&gt;getMethod() === 'POST') {
      if ($request-&gt;request-&gt;has($form-&gt;getName())
          &amp;&amp; isset($request-&gt;request-&gt;get($form-&gt;getName())['category'])) {
              $form = $this-&gt;createForm(new MyType($request-&gt;request-&gt;get($form-&gt;getName())['category']));
      }
  
      // ...
  }
  </code></pre>
  
  <p>This works, but I cannot test it because it throws <code>IllegalArgumentException</code> when setting the value and just assumes default. Is there any better solution to this? Thanks in advance!</p>