title: Symfony2 OneToMany – Persist Data from embedded form
body: <p>I have a problem when I want to save data from a form to a database </p>
  
  <p>I have two simple entities User and Telephone</p>
  
  <p>A user can have many telephones
  A telephone can have only one user</p>
  
  <p>the database tables are:</p>
  
  <blockquote>
    <p>user [ id, name, email]</p>
    
    <p>telephone [id, user_id, phone_number]</p>
  </blockquote>
  
  <p>Also my form has the following fields</p>
  
  <ul>
  <li>a name</li>
  <li>an email</li>
  <li>and a phone number</li>
  </ul>
  
  <p>When I fill and submit the form, I get the following Exception</p>
  
  <blockquote>
    <p>An exception occurred while executing 'INSERT INTO telephone (phone_number, user_id) VALUES (?, ?)' with params [123456, null]:</p>
    
    <p>SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'user_id' cannot be null</p>
  </blockquote>
  
  <p>From the debugger bar I see 4 queries was executed </p>
  
  <ol>
  <li>START TRANSACTION</li>
  <li>INSERT INTO user (name, email) 
  VALUES 
  (?, ?)
  Parameters: { 1: ‘name’, 2: email@yahoogmail.com } </li>
  <li>INSERT INTO telephone (phone_number, user_id) 
  VALUES 
  (?, ?)
  Parameters: { 1: 123456, 2: null } </li>
  <li>ROLLBACK</li>
  </ol>
  
  <p>I understand why this exception occurred but I don’t understand why the user_id gets NULL value. </p>
  
  <p>Here is my code
  (I omit getter , setters and annotations from some properties)</p>
  
  <p>User Entity</p>
  
  <pre><code>class User
  {
  
  private $name;
  
  private $email;
  
  /**
   * @var integer
   *
   * @ORM\Column(name="id", type="integer")
   * @ORM\Id
   * @ORM\GeneratedValue(strategy="IDENTITY")
   */
  private $id;
  
  /** 
   * @var \Acme\FormBundle\Entity\Telephone
   *
   * @ORM\OneToMany(targetEntity="Acme\FormBundle\Entity\Telephone", mappedBy="user", cascade={"ALL"})
   */
  private $telephones;
  
  /**
   * Constructor
   */
  public function __construct()
  {
      $this-&gt;telephones = new \Doctrine\Common\Collections\ArrayCollection();
  }
  
  /**
   * Add telephones
   *
   * @param \Acme\FormBundle\Entity\Telephone $telephones
   * @return User
   */
  public function addTelephone(\Acme\FormBundle\Entity\Telephone $telephones)
  {
      $this-&gt;telephones[] = $telephones;
      $telephones-&gt;setUser($this);
  
      return $this;
  }
  
  /**
   * Remove telephones
   *
   * @param \Acme\FormBundle\Entity\Telephone $telephones
   */
  public function removeTelephone(\Acme\FormBundle\Entity\Telephone $telephones)
  {
      $this-&gt;telephones-&gt;removeElement($telephones);
  }
  
  /**
   * Get telephones
   *
   * @return \Doctrine\Common\Collections\Collection 
   */
  public function getTelephones()
  {
      return $this-&gt;telephones;
  }
  }
  </code></pre>
  
  <p>Telephone Entity</p>
  
  <pre><code>class Telephone
  {
  private $phoneNumber;
  
  /**
   * @var integer
   *
   * @ORM\Column(name="id", type="integer")
   * @ORM\Id
   * @ORM\GeneratedValue(strategy="IDENTITY")
   */
  private $id;
  
  /**
   * @var \Acme\FormBundle\Entity\User
   *
   * @ORM\ManyToOne(targetEntity="Acme\FormBundle\Entity\User", inversedBy="telephones")
   * @ORM\JoinColumns({
   *   @ORM\JoinColumn(name="user_id", referencedColumnName="id")
   * })
   */
  private $user;
  
  /**
   * Set user
   *
   * @param \Acme\FormBundle\Entity\User $user
   * @return Telephone
   */
  public function setUser(\Acme\FormBundle\Entity\User $user = null)
  {
      $this-&gt;user = $user;
  
      return $this;
  }
  
  /**
   * Get user
   *
   * @return \Acme\FormBundle\Entity\User 
   */
  public function getUser()
  {
      return $this-&gt;user;
  }
  } 
  </code></pre>
  
  <p>UserType</p>
  
  <pre><code>class UserType extends AbstractType
  {
  public function buildForm(FormBuilderInterface $builder, array $options)
  {
      $builder-&gt;add('name')
          -&gt;add('email')
          -&gt;add('telephones', 'collection', array('type' =&gt; new TelephoneType()))
          -&gt;add('save it', 'submit');
  }
  
  public function setDefaultOptions(OptionsResolverInterface $resolver)
  {
      $resolver-&gt;setDefaults(array(
          'data_class' =&gt; 'Acme\FormBundle\Entity\User',
          ));
  }
  
  public function getName()
  {
      return 'user';
  }
  }
  </code></pre>
  
  <p>TelephoneType</p>
  
  <pre><code>class TelephoneType extends AbstractType
  {
  public function buildForm(FormBuilderInterface $builder, array $options)
  {
      $builder-&gt;add('phoneNumber');
  
  }
  
  public function setDefaultOptions(OptionsResolverInterface $resolver)
  {
      $resolver-&gt;setDefaults(array(
          'data_class' =&gt; 'Acme\FormBundle\Entity\Telephone',
          ));
  }
  
  public function getName()
  {
      return 'telephone';
  }
  }
  </code></pre>
  
  <p>and my controller</p>
  
  <pre><code>class DefaultController extends Controller
  {
  public function indexAction(Request $request)
  {
      $user = new User();
      $Telephone1 = new Telephone(); 
  
      $user-&gt;getTelephones()-&gt;add($Telephone1);
  
      $form = $this-&gt;createForm(new UserType(), $user);
  
      $form-&gt;handleRequest($request);
  
      if ($form-&gt;isValid()) {
  
          $em = $this-&gt;getDoctrine()-&gt;getManager();
          $em-&gt;persist($user);
          $em-&gt;flush();
  
      }
  
      return $this-&gt;render('AcmeFormBundle:Default:index.html.twig', array(
          'form' =&gt; $form-&gt;createView(),
          ));
  }
  }
  </code></pre>
  
  <p>Sorry for this long post </p>
  
  <p>Could anyone help me? </p>
  
  <p>I would appreciate it alot!  </p>