title: Symfony 2.7 - multiple nested/embedded Forms
body: <p>I would really appreciate if someone could help me. I spend some hours with this problem and could not find a solution. </p>
  
  <p>The code works fine (see below), as long as I don't need a second AddressType Class within PersonType Class. Something like this does not work:</p>
  
  <pre><code>// PersonType:
         $builder
              -&gt;add('firstname', 'text')
              -&gt;add('middlename', 'text')
              -&gt;add('lastname', 'text')
              -&gt;add('address', new AddressType())
              -&gt;add('address', new AddressType());
  </code></pre>
  
  <p>Multiple FormTypes of the same Type will have the same HTML-IDs so Symfony does not render the second address. I have several questions on that topic:</p>
  
  <ol>
  <li><p>Do I need the CollectionType even if I need only two address or is there another way (I don't need the user to be able to add dynamically another address)?</p></li>
  <li><p>Let's assume I need the CollectionType. At the beginning a CollectionType is empty. But I need two addresses from the start. I found the following in the Symfony-Documentation to create some collection items from the start: <a href="http://symfony.com/doc/2.7/form/form_collections.html" rel="nofollow noreferrer">Form Collections</a></p>
  
  <pre><code>// Controller:
  $task = new Task();
  // dummy code - this is here just so that the Task has some tags
  // otherwise, this isn't an interesting example
  $tag1 = new Tag();
  $tag1-&gt;setName('tag1');
  $task-&gt;getTags()-&gt;add($tag1);
  $tag2 = new Tag();
  $tag2-&gt;setName('tag2');
  $task-&gt;getTags()-&gt;add($tag2);
  </code></pre></li>
  </ol>
  
  <p>Now, please look at my controller. I don't even create a entity. I only create the main FormType which has all other Formtypes embedded. How or where can I create the two addresses? Or even my whole Controller-Code is wrong?</p>
  
  <ol start="3">
  <li><p>Is there a solution to tell symfony that the first address is not the same as the second address? How can I set the name/id of each AddressType? (This <a href="https://stackoverflow.com/a/18732386/3332997">solution</a> does not work anymore.)</p></li>
  <li><p>Is the form generation really ok in my controller? I don't pass a entity or an array to the form. It works, but I wonder why.... Otherwise I don't know how to pass all the entities I need to the form (contract, person, address, customer, payment, etc.).</p></li>
  </ol>
  
  <p>Thanks in advance!</p>
  
  <p><strong>Controller:</strong></p>
  
  <pre><code>class DefaultController extends Controller{
  /**
   * @return array
   * @Route("/private")
   * @Template("DmmGenericFormBundle:Default:index.html.twig")
   */
  public function indexAction(Request $request)
  {
      // This formtype class has all other form type classes
      $privateRentDepositForm = new PrivateRentDepositType();
  
      $form = $this-&gt;createForm($privateRentDepositForm);
  
      $form-&gt;handleRequest($request);
  
      if($form-&gt;isValid()){
  
          $contract =          $form-&gt;get('contract')-&gt;getData();
          $privateContractDetails = $form-&gt;get('privateContractDetails')-&gt;getData();
  
          $customer =          $form-&gt;get('customer')-&gt;getData();
          $customerPerson =    $form-&gt;get('customer')-&gt;get('person')-&gt;getData();
  
          $privateRealEstate =          $form-&gt;get('privateRealEstate')-&gt;getData();
          $privateRealEstateAddress =   $form-&gt;get('privateRealEstate')-&gt;get('address')-&gt;getData();
  
          $landlord =          $form-&gt;get('privateRealEstate')-&gt;get('landlord')-&gt;getData();
          $landlordPerson =    $form-&gt;get('privateRealEstate')-&gt;get('landlord')-&gt;get('person')-&gt;getData();
  
          $caretakerPerson =   $form-&gt;get('privateRealEstate')-&gt;get('landlord')-&gt;get('caretaker')-&gt;get('person')-&gt;getData();
  
          $payment =           $form-&gt;get('payment')-&gt;getData();
  
          $contract-&gt;addPerson($customerPerson);
          $contract-&gt;addPerson($landlordPerson);
          $contract-&gt;addPerson($caretakerPerson);
          $contract-&gt;setPrivateContractDetails($privateContractDetails);
  
          $customer-&gt;setPayment($payment);
  
          $landlord-&gt;setPrivateRealEstate($privateRealEstate);
  
          $privateRealEstate-&gt;addCustomer($customer);
          $privateRealEstate-&gt;setLandlord($landlord);
  
  
          $em = $this-&gt;get('doctrine')-&gt;getManager();
          $em-&gt;persist($contract);
          $em-&gt;flush();
      }
      return array('form' =&gt; $form-&gt;createView());
  }
  </code></pre>
  
  <p><strong>Form Type Classes:</strong></p>
  
  <pre><code>class PrivateRentDepositType extends AbstractType
  {
      /**
       * @param FormBuilderInterface $builder
       * @param array $options
       */
      public function buildForm(FormBuilderInterface $builder, array $options)
      {
  
          $builder
              -&gt;add('contract', new ContractType())
              -&gt;add('privateContractDetails', new PrivateContractDetailsType())
              -&gt;add('customer', new CustomerType())
              -&gt;add('privateRealEstate', new PrivateRealEstateType())
              -&gt;add('payment', new PaymentType())
              -&gt;add('save', 'submit');
      }
  
      /**
       * @param OptionsResolverInterface $resolver
       */
      public function configureOptions(OptionsResolver $resolver)
      {  
          $resolver-&gt;setDefaults(array(
              'data_class' =&gt; null,
              'csrf_protection' =&gt; false
          ));   
      }
  
      /**
       * @return string
       */
      public function getName()
      {
          return 'FormStep';
      }
  }
  </code></pre>
  
  <p>Person Type Class:</p>
  
  <pre><code>class PersonType extends AbstractType
  {
      /**
       * @param FormBuilderInterface $builder
       * @param array $options
       */
      public function buildForm(FormBuilderInterface $builder, array $options)
      {
          $builder
              -&gt;add('firstname', 'text')
              -&gt;add('middlename', 'text')
              -&gt;add('lastname', 'text')
              -&gt;add('address', new AddressType());
  
      }
  
      /**
       * @param OptionsResolverInterface $resolver
       */
      public function configureOptions(OptionsResolver $resolver)
      {
          $resolver-&gt;setDefaults(
              [
                  'data_class' =&gt; 'Dmm\Bundle\GenericFormBundle\Entity\Person',
                  'config' =&gt; null,
              ]
          );
      }
  
      /**
       * @return string
       */
      public function getName()
      {
          return 'dmm_bundle_genericformbundle_person';
      }
  }
  </code></pre>
  
  <p>Address Type Class:</p>
  
  <pre><code>class AddressType extends AbstractType
  {
  
      /**
       * @param FormBuilderInterface $builder
       * @param array $options
       */
      public function buildForm(FormBuilderInterface $builder, array $options)
      {
          $builder
              -&gt;add('street', 'text')
              -&gt;add('housenumber', 'text')
              -&gt;add('zip', 'text')
              -&gt;add('city', 'text')
              -&gt;add('extra', 'text')
              -&gt;add('country', 'text')
              -&gt;add('postOfficeBox', 'integer')
          ;
      }
  
      /**
       * @param OptionsResolverInterface $resolver
       */
      public function configureOptions(OptionsResolver $resolver)
      {
          $resolver-&gt;setDefaults(
              [
                  'data_class' =&gt; 'Dmm\Bundle\GenericFormBundle\Entity\Address',
                  'config'     =&gt; null,
              ]
          );
      }
  
      /**
       * @return string
       */
      public function getName()
      {
          return 'dmm_bundle_genericformbundle_address';
      }
  }
  </code></pre>
  
  <p>Customer Type Class: </p>
  
  <pre><code>class CustomerType extends AbstractType
  {
      /**
       * @param FormBuilderInterface $builder
       * @param array $options
       */
      public function buildForm(FormBuilderInterface $builder, array $options)
      {
          $builder
              -&gt;add('person', new PersonType())
              -&gt;add('birthplace', 'text')
              -&gt;add('email', 'email')
              -&gt;add('phone', 'text');
  
      }
  
      /**
       * @param OptionsResolverInterface $resolver
       */
      public function configureOptions(OptionsResolver $resolver)
      {
          $resolver-&gt;setDefaults(
              [
                  'data_class' =&gt; 'Dmm\Bundle\GenericFormBundle\Entity\Customer',
                  'config'     =&gt; null,
              ]
          );
      }
  
      /**
       * @return string
       */
      public function getName()
      {
          return 'dmm_bundle_genericformbundle_customer';
      }
  }
  </code></pre>
  
  <p><strong>DB Associations</strong></p>
  
  <p>Contract:Person = 1:n (Owning Side: Person, ArrayCollection for Person in Contract)</p>
  
  <p>Person:Address = 1:n (Owning Side: Address, ArrayCollection for Address in Person)</p>
  
  <p>Person:Customer = 1:1 (Owning Side: Customer, Customer IS A Person)</p>
  
  <p><strong>Edit:</strong>
  Code edit for Solution 2 by Cerad
  <em>Controller - create all objects</em></p>
  
  <pre><code>   $contract = new Contract();
     $contractDetails = new PrivateContractDetails();
     $contract-&gt;setPrivateContractDetails($contractDetails);
  
  
     $customer1Person = new Person();
     $customer1Address1 = new Address();
     $customer1Address1-&gt;setAddressType('someAddress');
     $customer1Address2 = new Address();
     $customer1Address2-&gt;setAddressType('someAddress');
     $customer1Person-&gt;addAddress($customer1Address1); 
     $customer1Person-&gt;addAddress($customer1Address2);
     $contract-&gt;addPerson($customer1Person);
     $customer1 = new Customer();
     $customer1-&gt;setPerson($customer1Person); 
  
     $customer2Person = new Person();
     $customer2Address1 = new Address();
     $customer2Address1-&gt;setAddressType('someAddress');
     $customer2Address2 = new Address();
     $customer2Address2-&gt;setAddressType('someAddress');
     $customer2Person-&gt;addAddress($customer2Address1);
     $customer2Person-&gt;addAddress($customer2Address2);
     $contract-&gt;addPerson($customer2Person);
     $customer2 = new Customer();
     $customer2-&gt;setPerson($customer2Person); 
  
  
     $landlordPerson = new Person();
     $landlordPersonAddress = new Address();
     $landlordPersonAddress-&gt;setAddressType('someAddress');
     $landlordPerson-&gt;addAddress($landlordPersonAddress);
     $contract-&gt;addPerson($landlordPerson);
     $landlord = new Landlord();
     $landlord-&gt;setPerson($landlordPerson);
  
  
     $prEstate = new PrivateRealEstate();
     $prEstateAddress = new Address();
     $prEstateAddress-&gt;setAddressType('someAddress');
     $prEstate-&gt;setAddress($prEstateAddress); 
     $landlord-&gt;setPrivateRealEstate($prEstate); 
     $prEstate-&gt;addCustomer($customer1); 
     $prEstate-&gt;addCustomer($customer2);
  
  
     $caretakerPerson = new Person();
     $caretakerAddress = new Address();
     $caretakerAddress-&gt;setAddressType('someAddress');
     $caretakerPerson-&gt;addAddress($caretakerAddress);
     $contract-&gt;addPerson($caretakerPerson);
     $caretaker = new Caretaker();
     $caretaker-&gt;addLandlord($landlord);
     $caretaker-&gt;setPerson($caretakerPerson);
  
     $payment = new Payment();
     $customer1-&gt;setPayment($payment);
  
      $privateRentDepositForm = new PrivateRentDepositType();
  
  
      $form = $this-&gt;createForm($privateRentDepositForm, $contract);
  </code></pre>
  
  <p>And I replaced</p>
  
  <pre><code>-&gt;add('address', new AddressType());
  </code></pre>
  
  <p>with</p>
  
  <pre><code>-&gt;add('address', 'collection', array(
      'type' =&gt; new AddressType()
  ))
  </code></pre>
  
  <p>Now I get the following exception:
  The form's view data is expected to be of type scalar, array or an instance of \ArrayAccess, but is an instance of class Dmm\Bundle\GenericFormBundle\Entity\Contract. You can avoid this error by setting the "data_class" option to "Dmm\Bundle\GenericFormBundle\Entity\Contract" or by adding a view transformer that transforms an instance of class Dmm\Bundle\GenericFormBundle\Entity\Contract to scalar, array or an instance of \ArrayAccess.</p>
  
  <p>In ContractType the data_class is set to the right class. Only in PrivateRentDepositType the data_class is set to null. But PrivateRentDepositType is a collection of diffrent types. I tried to set the data_class to 'Dmm\Bundle\GenericFormBundle\Entity\Contract' but that leads to another excepiton: Neither the property "contract" nor one of the methods "getContract()", "contract()", "isContract()", "hasContract()", "__get()" exist and have public access in class "Dmm\Bundle\GenericFormBundle\Entity\Contract".</p>