title: Add / Remove input fields Dynamically to form (Symfony 3 Events / Ajax)
body: <p>I'm working on a small ads website, but I have this problem with <a href="https://symfony.com/doc/current/form/dynamic_form_modification.html" rel="nofollow noreferrer">Form Events</a> , when i try to add input fields dynamically.</p>
  
  <p>Here's the thing, I have an entity Ad : </p>
  
  <pre><code>/**
   * Ad
   *
   * @ORM\Table(name="ma_ad")
   * @ORM\Entity(repositoryClass="MA\PlatformBundle\Repository\AdRepository")
   * @ORM\HasLifecycleCallbacks()
   */
  class Ad
  {
  /**
   * @var int
   *
   * @ORM\Column(name="id", type="integer")
   * @ORM\Id
   * @ORM\GeneratedValue(strategy="AUTO")
   */
  private $id;
  
  /**
   * @var string
   *
   * @ORM\Column(name="title", type="string", length=255)
   * @Assert\Length(min=10)
   */
  private $title;
  
  /**
   * @ORM\ManyToOne(targetEntity="MA\PlatformBundle\Entity\Category")
   * @ORM\JoinColumn(nullable=false)
   */
  private $category;
  
  /** @var float
   *
   * @ORM\Column(name="speed", type="float")
   * @Assert\Valid()
   * @Assert\Range(min=0)
   */
  private $speed;
  
   * @var float
   *
   * @ORM\Column(name="area", type="float")
   * @Assert\Valid()
   * @Assert\Range(min=0)
   */
  private $area;
  </code></pre>
  
  <p>.
     .
     .
  Let's say i have two categories, Cars and Houses when the user select Cars the speed input field should be appear, when He choose Houses it's area input field and not speed.</p>
  
  <p>I tried what is on the <a href="https://symfony.com/doc/current/form/dynamic_form_modification.html" rel="nofollow noreferrer">documentary</a>  so this is my AdType :</p>
  
  <pre><code>class AdType extends AbstractType
  {
  /**
   * {@inheritdoc}
   */
  public function buildForm(FormBuilderInterface $builder, array $options)
  {
      /**
       *  @var \Doctrine\ORM\EntityManager $em
       */
      $em = $options['entity_manager'];
  
      $builder-&gt;add('title', TextType::class)
          -&gt;add('category', EntityType::class, array(
              'class' =&gt; 'MAPlatformBundle:Category',
              'choice_label' =&gt; 'name',
              'multiple' =&gt; false,
              'group_by' =&gt; 'category.name'
          ))
  
      $formModifier = function(FormInterface $form, Category $category = null) 
      {
              if( $category-&gt;getName() === "Cars" ){
                  $form-&gt;add('speed',TextType::class);
              } else if( $category-&gt;getName() === "Houses" ){
                  $form-&gt;add('area',TextType::class);
              }
      };
  
      $builder-&gt;addEventListener(
          FormEvents::PRE_SET_DATA, function (FormEvent $event) use ( $formModifier ) {
              $form = $event-&gt;getForm();
              $category = $event-&gt;getData()-&gt;getCategory();
              $formModifier($form, $category);
          }
      );
  
      $builder-&gt;get('category')-&gt;addEventListener(
          FormEvents::PRE_SUBMIT, 
          function( FormEvent $event ) use ( $formModifier, $em ){
              $id_category = $event-&gt;getData();
              $category = $em-&gt;getRepository("MAPlatformBundle:Category")-&gt;find($id_category);
              $form = $event-&gt;getForm()-&gt;getParent();
              $formModifier($form, $category);
          });
  
  /**
   * {@inheritdoc}
   */
  public function configureOptions(OptionsResolver $resolver)
  {
      $resolver-&gt;setDefaults(array(
          'data_class' =&gt; 'MA\PlatformBundle\Entity\Annonce',
          'entity_manager' =&gt; null,
      ));
  }
  </code></pre>
  
  <p>and finally the twig page : </p>
  
  <pre><code>{{ form_start( form, { 'attr': { 'class': 'form-ad' }}) }}
                {{ form_row(form.title) }}
                {{ form_row(form.category) }}
  
              &lt;div id="dynamic"&gt;
                  {{ form_rest(form) }}
              &lt;/div&gt;
              &lt;div class="form-group"&gt;
                &lt;div class="well"&gt;
                  {{ form_widget(form.save, {'attr': {'class': 'btn btn-common', 'value': 'Add'}} ) }}
                &lt;/div&gt; 
              &lt;/div&gt; 
  &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt;
  
  &lt;script&gt;
  $(document).ready(function(){
  var $category = $('#ma_platformbundle_ad_category');
  
  $category.change( function(){
      var $form = $(this).closest('form');
      var data = {
          'id_category': $category.val(),
      };
      $.ajax({
          url : "{{path('ma_platform_add')}}",
          type: 'POST',
          data : data,
          success: function (html) {
              $('#dynamic').replaceWith(
                  $(html).find('#dynamic')
                );
          }
      });
  });
  });
  </code></pre>
  
  <p></p>
  
  <p>So when i choose the category, nothing happened the form stays as it is.
  I tried to make it simple for you guys, so you can help me.
  Thanks in advance. </p>