title: Symfony Howto create a entity and add it to another?
body: <p>Hi and thank you for taking the time reading this.
  English is not my first language so I hope you'll excuse me for any errors.
  Currently I'm doing a project to get familiar with Symfony 3.</p>
  
  <p>This is what I'm trying to do:</p>
  
  <p>I have a  oneToMany relation, Game to PlayLog.
  The relation is established and I can view a list of dates in my games. </p>
  
  <p>I want to create a new PlayLog and be associated with the Game so I can access all my related PlayLogs via Game.
  A view is shown with the id of the game (log.html.twig)</p>
  
  <p><strong>My question:</strong>
  How do I create a new PlayLog with a form and date formField(dateType), and add it to an existing game?</p>
  
  <p>Update: with the current code I now get this error:</p>
  
  <blockquote>
    <p>An exception occurred while executing 'INSERT INTO play_log (date,
    game_id) VALUES (?, ?)' with params ["2017-03-04", null]:
    SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'game_id'
    cannot be null</p>
  </blockquote>
  
  <p>This is my code:</p>
  
  <p>--- entity/Game.php</p>
  
  <pre><code>&lt;?php
  
  namespace AppBundle\Entity;
  
  use Doctrine\ORM\Mapping as ORM;
  use Doctrine\Common\Collections\ArrayCollection;
  use Symfony\Component\Validator\Constraints as Assert;
  
  /**
   * Game
   *
   * @ORM\Table(name="game")
   * @ORM\Entity(repositoryClass="AppBundle\Repository\GameRepository")
   */
  class Game
  {
  
      /**
       * @ORM\OneToMany(targetEntity="PlayLog", mappedBy="game")
       */
      private $playlogs;
      public function __construct()
      {
          $this-&gt;playlogs = new ArrayCollection();
      }
  
      /**
       * @ORM\ManyToOne(targetEntity="Type", inversedBy="games")
       * @ORM\JoinColumn(name="type_id", referencedColumnName="id")
       */
      private $type;
  
  
      /**
       * @var int
       *
       * @ORM\Column(name="id", type="integer")
       * @ORM\Id
       * @ORM\GeneratedValue(strategy="AUTO")
       */
      private $id;
  
  
      /**
       * @var string
       * @Assert\NotBlank()
       * @Assert\Length(
       *     min = "3",
       *  max = "100"
       * )
       * @ORM\Column(name="name", type="string", length=255, unique=true)
       */
      private $name;
  
  
      /**
       * Get id
       *
       * @return int
       */
      public function getId()
      {
          return $this-&gt;id;
      }
  
      /**
       * Set name
       *
       * @param string $name
       *
       * @return Game
       */
      public function setName($name)
      {
          $this-&gt;name = $name;
  
          return $this;
      }
  
      /**
       * Get name
       *
       * @return string
       */
      public function getName()
      {
          return $this-&gt;name;
      }
  
      /**
       * @return mixed
       */
      public function getType()
      {
          return $this-&gt;type;
      }
  
      /**
       * @ORM\Column (options={"default" = none})
       * @param mixed $type
       */
      public function setType($type)
      {
          $this-&gt;type = $type;
      }
  
  
      /**
       * @return mixed
       */
      public function getPlaylogs()
      {
          return $this-&gt;playlogs;
      }
  
      /**
       * @param mixed $playlogs
       */
      public function setPlaylogs($playlogs)
      {
          $this-&gt;playlogs = $playlogs;
      }
  
      public function addPlayLog(PlayLog $playlog)
      {
          $this-&gt;playlog-&gt;add($playlog);
          $playlog-&gt;setPlayLogs($this);
      }
  
  }
  </code></pre>
  
  <p>--- entity/PlayLog.php</p>
  
  <pre><code>&lt;?php
  
  namespace AppBundle\Entity;
  
  use Doctrine\ORM\Mapping as ORM;
  
  /**
   * PlayLog
   *
   * @ORM\Table(name="play_log")
   * @ORM\Entity(repositoryClass="AppBundle\Repository\PlayLogRepository")
   */
  class PlayLog
  {
  
      /**
       * @ORM\ManyToOne(targetEntity="Game", inversedBy="playlogs")
       * @ORM\JoinColumn(name="game_id", referencedColumnName="id")
       */
      private $game;
  
  
      /**
       * @var int
       *
       * @ORM\Column(name="id", type="integer")
       * @ORM\Id
       * @ORM\GeneratedValue(strategy="AUTO")
       */
      private $id;
  
      /**
       * @var \DateTime
       *
       * @ORM\Column(name="date", type="date")
       */
      private $date;
  
      /**
       * @var int
       *
       * @ORM\Column(name="game_id", type="integer")
       */
      private $gameId;
  
  
      /**
       * Get id
       *
       * @return int
       */
      public function getId()
      {
          return $this-&gt;id;
      }
  
      /**
       * Set date
       *
       * @param \DateTime $date
       *
       * @return PlayLog
       */
      public function setDate($date)
      {
          $this-&gt;date = $date;
  
          return $this;
      }
  
      /**
       * Get date
       *
       * @return \DateTime
       */
      public function getDate()
      {
          return $this-&gt;date;
      }
  
      /**
       * Set gameId
       *
       * @param integer $gameId
       *
       * @return PlayLog
       */
      public function setGameId($gameId)
      {
          $this-&gt;gameId = $gameId;
  
          return $this;
      }
  
      /**
       * Get gameId
       *
       * @return int
       */
      public function getGameId()
      {
          return $this-&gt;gameId;
      }
  
  
      public function addGame(Game $game)
      {
          $this-&gt;games-&gt;add($game);
          $game-&gt;setType($this);
      }
      public function removeGame(Game $game)
      {
          $this-&gt;games-&gt;removeElement($game);
      }
  
  
  
  }
  </code></pre>
  
  <p>--- GameController.php</p>
  
  <pre><code>&lt;?php
  
  namespace AppBundle\Controller;
  
  use AppBundle\Entity\Game;
  use AppBundle\Entity\PlayLog;
  use AppBundle\Entity\Type;
  use AppBundle\Form\GameType;
  use Symfony\Bundle\FrameworkBundle\Controller\Controller;
  use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
  use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
  use Symfony\Component\Form\Extension\Core\Type\SubmitType;
  use Symfony\Component\Form\Extension\Core\Type\DateType;
  use Symfony\Component\HttpFoundation\Request;
  /**
   * Game controller.
   *
   * @Route("game")
   */
  class GameController extends Controller
  {
      /**
       * Lists all game entities.
       *
       * @Route("/", name="game_index")
       * @Method("GET")
       */
      public function indexAction(Request $request)
      {
          $em = $this-&gt;getDoctrine()-&gt;getManager();
  //        $games = $em-&gt;getRepository('AppBundle:Game')-&gt;findAll();
          $dql = "SELECT game FROM AppBundle:Game game JOIN game.type type ORDER BY game.name";
          $query = $em-&gt;createQuery($dql);
          /*
           * @var $paginator \Knp\Component\Pager\Paginator
           */
          $paginator = $this-&gt;get('knp_paginator');
          $result = $paginator-&gt;paginate(
               $query,
              $request-&gt;query-&gt;getInt('page', 1),
              $request-&gt;query-&gt;getInt('limit', 25)
          );
  //        dump(get_class($paginator));
  
          return $this-&gt;render('game/index.html.twig', array(
              'games' =&gt; $result,
              'max_limit_error' =&gt; 25
          ));
      }
  
      /**
       * Creates a new game entity.
       *
       * @Route("/new", name="game_new")
       * @Method({"GET", "POST"})
       */
      public function newAction(Request $request)
      {
  
          $game = new Game();
  
          $form = $this-&gt;createForm('AppBundle\Form\GameType', $game);
          $form-&gt;handleRequest($request);
  
          if ($form-&gt;isSubmitted() &amp;&amp; $form-&gt;isValid()) {
              $em = $this-&gt;getDoctrine()-&gt;getManager();
              $em-&gt;persist($game);
              $em-&gt;flush($game);
  
              return $this-&gt;redirectToRoute('game_show', array('id' =&gt; $game-&gt;getId()));
          }
  
          return $this-&gt;render('game/new.html.twig', array(
              'game' =&gt; $game,
              'form' =&gt; $form-&gt;createView(),
          ));
      }
  
      /**
       * Finds and displays a game entity.
       *
       * @Route("/{id}", name="game_show")
       * @Method("GET")
       */
      public function showAction(Game $game)
      {
          $deleteForm = $this-&gt;createDeleteForm($game);
  
  
          return $this-&gt;render('game/show.html.twig', array(
              'game' =&gt; $game,
              'delete_form' =&gt; $deleteForm-&gt;createView(),
          ));
      }
  
      /**
       * Displays a form to edit an existing game entity.
       *
       * @Route("/{id}/edit", name="game_edit")
       * @Method({"GET", "POST"})
       */
      public function editAction(Request $request, Game $game)
      {
          $deleteForm = $this-&gt;createDeleteForm($game);
          $editForm = $this-&gt;createForm('AppBundle\Form\GameType', $game);
          $editForm-&gt;handleRequest($request);
  
          if ($editForm-&gt;isSubmitted() &amp;&amp; $editForm-&gt;isValid()) {
              $this-&gt;getDoctrine()-&gt;getManager()-&gt;flush();
  
              return $this-&gt;redirectToRoute('game_show', array('id' =&gt; $game-&gt;getId()));
          }
  
          return $this-&gt;render('game/edit.html.twig', array(
              'game' =&gt; $game,
              'edit_form' =&gt; $editForm-&gt;createView(),
              'delete_form' =&gt; $deleteForm-&gt;createView(),
  
          ));
      }
  
      /**
       * Displays a form to edit an existing game entity.
       *
       * @Route("/{id}/log", name="game_log")
       * @Method({"GET", "POST"})
       */
      public function addLogAction(Request $request, Game $game)
      {
          $playlog = new PlayLog();
          $form = $this-&gt;createForm(GameType::class, $game);
          $form-&gt;handleRequest($request);
          if($form-&gt;isSubmitted() &amp;&amp; $form-&gt;isValid()) {
  
              //Save playLog
              $em = $this-&gt;getDoctrine()-&gt;getManager();
              $em-&gt;persist($playlog);
              $em-&gt;flush();
  
          }
          // Render / return view incl. formulier.
          return $this-&gt;render('game/log.html.twig', array(
              'game' =&gt; $game,
              'form' =&gt; $form-&gt;createView(),
          ));
      }
  
      /**
       * Deletes a game entity.
       *
       * @Route("/{id}", name="game_delete")
       * @Method("DELETE")
       */
      public function deleteAction(Request $request, Game $game)
      {
          $form = $this-&gt;createDeleteForm($game);
          $form-&gt;handleRequest($request);
  
          if ($form-&gt;isSubmitted() &amp;&amp; $form-&gt;isValid()) {
              $em = $this-&gt;getDoctrine()-&gt;getManager();
              $em-&gt;remove($game);
              $em-&gt;flush($game);
          }
  
          return $this-&gt;redirectToRoute('game_index');
      }
  
      /**
       * Creates a form to delete a game entity.
       *
       * @param Game $game The game entity
       *
       * @return \Symfony\Component\Form\Form The form
       */
      private function createDeleteForm(Game $game)
      {
          return $this-&gt;createFormBuilder()
              -&gt;setAction($this-&gt;generateUrl('game_delete', array('id' =&gt; $game-&gt;getId())))
              -&gt;setMethod('DELETE')
              -&gt;getForm()
          ;
      }
  }
  </code></pre>
  
  <p>--- PlayLogController.php</p>
  
  <pre><code>&lt;?php
  
  namespace AppBundle\Controller;
  
  use AppBundle\Entity\PlayLog;
  use Symfony\Bundle\FrameworkBundle\Controller\Controller;
  use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
  use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;use Symfony\Component\HttpFoundation\Request;
  
  /**
   * Playlog controller.
   *
   * @Route("playlog")
   */
  class PlayLogController extends Controller
  {
      /**
       * Lists all playLog entities.
       *
       * @Route("/", name="playlog_index")
       * @Method("GET")
       */
      public function indexAction()
      {
          $em = $this-&gt;getDoctrine()-&gt;getManager();
  
          $playLogs = $em-&gt;getRepository('AppBundle:PlayLog')-&gt;findAll();
  
          return $this-&gt;render('playlog/index.html.twig', array(
              'playLogs' =&gt; $playLogs,
          ));
      }
     /**
       * Creates a new playLog entity.
       *
       * @Route("/{gameId}/new", name="playlog_new")
       * @Method({"GET", "POST"})
       */
      public function newAction(Request $request, $gameId)
      {
  
          $playlog = new PlayLog();
  
          $form = $this-&gt;createForm('AppBundle\Form\PlayLogType', $playlog);
          $form-&gt;handleRequest($request);
  
          $playlog-&gt;setGameId($gameId);
          echo $playlog-&gt;getGameId()."!";
          if ($form-&gt;isSubmitted() &amp;&amp; $form-&gt;isValid()) {
              $em = $this-&gt;getDoctrine()-&gt;getManager();
              $em-&gt;persist($playlog);
              $em-&gt;flush();
  //            return $this-&gt;redirectToRoute('game_show', array('id' =&gt; $gameId));
          }
  
          return $this-&gt;render('playlog/new.html.twig', array(
              'playLog' =&gt; $playlog,
              'form' =&gt; $form-&gt;createView(),
          ));
      }
          return $this-&gt;render('playlog/new.html.twig', array(
              'playLog' =&gt; $playLog,
              'form' =&gt; $form-&gt;createView(),
          ));
      }
  
      /**
       * Finds and displays a playLog entity.
       *
       * @Route("/{id}", name="playlog_show")
       * @Method("GET")
       */
      public function showAction(PlayLog $playLog)
      {
          $deleteForm = $this-&gt;createDeleteForm($playLog);
  
          return $this-&gt;render('playlog/show.html.twig', array(
              'playLog' =&gt; $playLog,
              'delete_form' =&gt; $deleteForm-&gt;createView(),
          ));
      }
  
      /**
       * Displays a form to edit an existing playLog entity.
       *
       * @Route("/{id}/edit", name="playlog_edit")
       * @Method({"GET", "POST"})
       */
      public function editAction(Request $request, PlayLog $playLog)
      {
          $deleteForm = $this-&gt;createDeleteForm($playLog);
          $editForm = $this-&gt;createForm('AppBundle\Form\PlayLogType', $playLog);
          $editForm-&gt;handleRequest($request);
  
          if ($editForm-&gt;isSubmitted() &amp;&amp; $editForm-&gt;isValid()) {
              $this-&gt;getDoctrine()-&gt;getManager()-&gt;flush();
  
              return $this-&gt;redirectToRoute('playlog_edit', array('id' =&gt; $playLog-&gt;getId()));
          }
  
          return $this-&gt;render('playlog/edit.html.twig', array(
              'playLog' =&gt; $playLog,
              'edit_form' =&gt; $editForm-&gt;createView(),
              'delete_form' =&gt; $deleteForm-&gt;createView(),
          ));
      }
  
      /**
       * Deletes a playLog entity.
       *
       * @Route("/{id}", name="playlog_delete")
       * @Method("DELETE")
       */
      public function deleteAction(Request $request, PlayLog $playLog)
      {
          $form = $this-&gt;createDeleteForm($playLog);
          $form-&gt;handleRequest($request);
  
          if ($form-&gt;isSubmitted() &amp;&amp; $form-&gt;isValid()) {
              $em = $this-&gt;getDoctrine()-&gt;getManager();
              $em-&gt;remove($playLog);
              $em-&gt;flush();
          }
  
          return $this-&gt;redirectToRoute('playlog_index');
      }
  
      /**
       * Creates a form to delete a playLog entity.
       *
       * @param PlayLog $playLog The playLog entity
       *
       * @return \Symfony\Component\Form\Form The form
       */
      private function createDeleteForm(PlayLog $playLog)
      {
          return $this-&gt;createFormBuilder()
              -&gt;setAction($this-&gt;generateUrl('playlog_delete', array('id' =&gt; $playLog-&gt;getId())))
              -&gt;setMethod('DELETE')
              -&gt;getForm()
          ;
      }
  }
  </code></pre>
  
  <p>--- game/log.html.twig</p>
  
  <pre><code>{% extends 'base.html.twig' %}
  {% block content %}
      Adding log for {{ game.name }}
      {{ form_widget(form.playlogs) }}
  
      &lt;input type="submit" value="Create" class="btn btn-default pull-left" /&gt;
  {% endblock content %}
  </code></pre>
  
  <p>--- PlayLogType.php</p>
  
  <pre><code>&lt;?php
  
  namespace AppBundle\Form;
  
  use AppBundle\Entity\PlayLog;
  use Symfony\Component\Form\AbstractType;
  use Symfony\Component\Form\FormBuilderInterface;
  use Symfony\Component\OptionsResolver\OptionsResolver;
  
  class PlayLogType extends AbstractType
  {
      /**
       * {@inheritdoc}
       */
      public function buildForm(FormBuilderInterface $builder, array $options)
      {
          $builder-&gt;add('date');
      }
  
      /**
       * {@inheritdoc}
       */
      public function configureOptions(OptionsResolver $resolver)
      {
          $resolver-&gt;setDefaults(array(
              'data_class' =&gt; PlayLog::class
          ));
      }
  
      /**
       * {@inheritdoc}
       */
      public function getBlockPrefix()
      {
          return 'appbundle_playlog';
      }
  
  
  }
  </code></pre>
  
  <p>--- GameType.php</p>
  
  <pre><code>   &lt;?php
  
      namespace AppBundle\Form;
  
      use AppBundle\Entity\PlayLog;
      use Symfony\Component\Form\Extension\Core\Type\CollectionType;
      use Symfony\Component\Form\Extension\Core\Type\SubmitType;
      use Symfony\Component\Form\Extension\Core\Type\TextType;
      use Symfony\Bridge\Doctrine\Form\Type\EntityType;
      use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
      use Symfony\Component\Form\AbstractType;
      use Symfony\Component\Form\FormBuilderInterface;
      use Symfony\Component\OptionsResolver\OptionsResolver;
  
      class GameType extends AbstractType
      {
          /**
           * {@inheritdoc}
           */
          public function buildForm(FormBuilderInterface $builder, array $options)
          {
              $builder
                  -&gt;add('name', TextType::class, [
                      'attr' =&gt; [
                          'class' =&gt; 'form-control',
                      ],
                  ]);
              $builder
                  -&gt;add('type', EntityType::class, [
                      'class' =&gt; 'AppBundle:Type',
                      'choice_label' =&gt; function ($type) {
                          return $type-&gt;getName();
                      },
                      'multiple' =&gt; false,
                      'expanded' =&gt; false,
                      'attr' =&gt; [
                          'class' =&gt; 'form-control',
                      ],
  
                  ]);
  
              $builder-&gt;add('playlogs', CollectionType::class, array(
                  'entry_type' =&gt; PlayLogType::class,
                  'label' =&gt; false
              ));
  
  
          }
  
          /**
           * {@inheritdoc}
           */
          public function configureOptions(OptionsResolver $resolver)
          {
              $resolver-&gt;setDefaults(array(
                  'data_class' =&gt; 'AppBundle\Entity\Game'
              ));
          }
  
          /**
           * {@inheritdoc}
           */
          public function getBlockPrefix()
          {
              return 'appbundle_game';
          }
  
  
      }
  </code></pre>