title: New entities added using Symfony2 many-to-one embedded forms not being saved
body: <p>This is related to my <a href="https://stackoverflow.com/questions/11015952/using-jquery-in-symfony2-php-template#comment14431438_11015952">earlier question about embedded forms</a>.  As advised, I switched to a twig template and now everything is displaying as expected and the link to add a new empty form is working correctly.  The problem is that when I try to save a new record, it doesn't work (although edits to existing entities are saved).  </p>
  
  <p>There are several points where I may have gone wrong, so I'm going to ask questions as I go along.</p>
  
  <p>Here's some background:<br>
  A study can have many participants (i.e. a Study entity has a OneToMany relationship with the entity Participant).  In the database, each Participant record has the foreign key link from the column  "study" to the "study_id" column of a record in the Study table, making it the owning side of the relation.  The annotation in the classes should reflect this relationship.</p>
  
  <p>Study class:</p>
  
  <pre><code>namespace MyBundle\Entity;
  use Doctrine\ORM\Mapping as ORM;
  
  /**
  * CRUK\MyBundle\Entity\Study
  *
  * @ORM\Table(name="study")
  * @ORM\Entity
  */
  class Study
  {
      /**
      * @var integer $id
      *
      * @ORM\Column(name="study_id", type="integer", nullable=false)
      * @ORM\Id
      * @ORM\GeneratedValue(strategy="IDENTITY")
      */
      private $id;
  
      /**
       * @var string $studyName
       *
       * @ORM\Column(name="study_name", type="string", length=50, nullable=false)
      */
      private $studyName;
  
      /*
       * @ORM\OneToMany(targetEntity="Participant", mappedBy="study", cascade={"persist"})
       * 
       * @var ArrayCollection $participants
       */
       protected $participants;
  
       public function __construct() 
      {
          $this-&gt;participants = new ArrayCollection();
      }
  
      public function setParticipants(ArrayCollection $participants)
      {
          foreach($participants as $participant)  {
              $participant-&gt;setStudy($this);
          }
          $this-&gt;participants = $participants;
      }
  
      /**
       * @return ArrayCollection A Doctrine ArrayCollection
       */
      public function getParticipants()
      {
          return $this-&gt;participants;
      }
  }
  </code></pre>
  
  <p>My Participant class:</p>
  
  <pre><code>namespace MyBundle\Entity;
  use Doctrine\ORM\Mapping as ORM;
  
  /**
   * CRUK\SampleTrackingBundle\Entity\Participant
   *
   * @ORM\Table(name="participant")
   * @ORM\Entity
   */
   class Participant
  {
      /**
       * @var integer $id
       *
       * @ORM\Column(name="participant_id", type="integer", nullable=false)
       * @ORM\Id
       * @ORM\GeneratedValue(strategy="IDENTITY")
       */
      private $id;
      ...
  
     /**
      * @var study
      *
      * @ORM\ManyToOne(targetEntity="Study", inversedBy="participants") 
      * @ORM\JoinColumn(name="study", referencedColumnName="study_id")
      * 
      */
      private $study;
  
      //setters and getters...
  }
  </code></pre>
  
  <p>First of all, are these annotations correct? (I'm pretty sure I got the whole owning/inverse many-to-one/one-to many relationship straight in my head, but I could be mistaken)</p>
  
  <p>My controller:</p>
  
  <pre><code>Class StudyController extends Controller
  {
      ...
      public function addParticipantsAction($id)
      {
          $em = $this-&gt;getDoctrine()-&gt;getEntityManager();
  
          $entity = $em-&gt;getRepository('MyBundle:Study')-&gt;find($id);
  
          if (!$entity) {
              throw $this-&gt;createNotFoundException('Unable to find Study id='.$id);
          }
          $participantArray = $em-&gt;getRepository('MyBundle:Participant')-&gt;findByStudy($id);
          //this is supposed to return a Doctrine ArrayCollection, but for some reason, returns an array
          // This needs to be converted to an ArrayCollection
          $participants = new ArrayCollection();
          foreach ($participantArray as $participant) {
             $participants-&gt;add($participant);
          }
          $entity-&gt;setParticipants($participants);
          $form   = $this-&gt;createForm(new StudyType(), $entity);
          $request = $this-&gt;getRequest();
  
          if ('POST' === $request-&gt;getMethod()) {
              $form-&gt;bindRequest($request);
              if ($form-&gt;isValid()) {
                  $em-&gt;persist($entity);
                  $em-&gt;flush();
              }
          }
  
          return $this-&gt;render('MyBundle:Study:addParticipants.html.twig', array(
              'form' =&gt; $form-&gt;createView(),
              'entity' =&gt; $entity
          ));
      }
  ...
  }   
  </code></pre>
  
  <p>At this point I have to ask why it is neccessary to explicitly fetch the collection of participants and use it to set the collection on the study entity?  Before I added that code, $entity->getParticipants() would return null (even when I know there were several participants with the foreign key set for the study). I have two other tables in a many-to-many relationship where the collections seem to come up automatically just by having the correct annotations in the entity classes.  Is this a difference between a many-to-many mapping vs. a many-to-one, or have I messed up the annotation somehow?</p>
  
  <p>I'm not sure if the rest of the code will help, but here's some more:
  My study form class:</p>
  
  <pre><code>class StudyType extends AbstractType
  {
      public function buildForm(FormBuilder $builder, array $options)
      {
          $builder
              -&gt;add('studyName', null, array('label'=&gt; 'Study Name:'))
              -&gt;add('participants', 'collection', array(
                  'type'=&gt; new ParticipantType(), 
                  'allow_add'=&gt;true,
                  'by_reference'=&gt;false
                ));
      }
  
      public function getName()
      {
          return 'study';
      }
  
      public function getDefaultOptions(array $options) 
      {
          return array(
              'data_class' =&gt; 'MyBundle\Entity\Study',
          );
      }
  }
  </code></pre>
  
  <p>My embedded form class:</p>
  
  <pre><code>class ParticipantType extends AbstractType
  {
      public function buildForm(FormBuilder $builder, array $options)
      {
      $builder
          -&gt;add('participantId','text', array('label'=&gt;'Participant ID'))
  
          ));
      }
  
      public function getName()
      {
          return 'participant';
      }
  
      public function getDefaultOptions(array $options) 
      {
        return array(
            'data_class' =&gt; 'MyBundle\Entity\Participant',
        );
      }
  }    
  </code></pre>
  
  <p>My template:</p>
  
  <pre><code>{% extends 'MyBundle::base.html.twig' %}
  
  {% block body%}
    &lt;form action="{{ path('study_addparticipants', { 'id': entity.id }) }}" method="POST" {{ form_enctype(form) }}&gt;
      &lt;!-- renders global errors --&gt;
      {{ form_errors(form)  }}
      &lt;h2&gt;Study&lt;/h2&gt;
      {{ form_label(form.studyName) }}
      {{ form_errors(form.studyName) }}
      {{ form_widget(form.studyName) }}
  
      &lt;h3&gt;Participants in this study&lt;/h3&gt;
      &lt;ul class="participants" data-prototype="{{ form_widget(form.participants.get('prototype')) | e }}"&gt;
          {% for participant in form.participants %}
              &lt;li&gt;{{form_row(participant) }}&lt;/li&gt;
          {% endfor %}
      &lt;/ul&gt;
      {{ form_rest(form) }}
      &lt;button type="submit"&gt;Save Changes&lt;/button&gt;
    &lt;/form&gt; 
  {% endblock%}
  
  {% block javascripts %}
     {# parent block includes jQuery #}
     {{ parent() }}
  
    &lt;script type='text/javascript'&gt;
        jQuery(document).ready(function() {
          // keep track of how many participant fields have been rendered
          var collectionHolder = $('ul.participants');
          var $addLink = $('&lt;a href="#" class="add_participant_link"&gt;Add new Participant&lt;/a&gt;');
          var $newLinkLi = $('&lt;li&gt;&lt;/li&gt;'). append($addLink);
          collectionHolder.append($newLinkLi);
          $addLink.on('click', function(e) {
             e.preventDefault();
             addParticipantForm(collectionHolder, $newLinkLi);
          });
        });
  
        function addParticipantForm(collectionHolder, $newLinkLi) {
           // Get the data-prototype we explained earlier
          var prototype = collectionHolder.attr('data-prototype');
  
         // Replace '$$name$$' in the prototype's HTML to
         // instead be a number based on the current collection's length.
         var newForm = prototype.replace(/\$\$name\$\$/g, collectionHolder.children().length);
  
        // Display the form in the page in an li, before the "Add a tag" link li
        var $newFormLi = $('&lt;li&gt;&lt;/li&gt;').append(newForm);
        $newLinkLi.before($newFormLi);
      }
    &lt;/script&gt;
  
  {% endblock %}
  </code></pre>
  
  <p>So, the form displays correctly and when I click the "Add new participant" link, an empty participant form is appended. Changes to the Study and exisitng participant records are saved. There are no errors, but any new participants are not saved.</p>
  
  <p>I have read many similar questions to this one and as far as I know, incorporated everything that should make this work.  I've obviously missed something, so would appreciate any suggestions on how to put this right.</p>
  
  <p>Many Thanks. </p>