简体   繁体   中英

Symfony2 Form Entity OneToMany with only one entity doesn't work

I've got two tables: session and game (one session can have multiple games)

After I add a session it renders my game form. But now I have a strange behaviour: when I took a EntityType Form where all my session are loaded, the game is saved correctly in my database. But when I only load one session in my form, the session_id field in database is NULL.

Game Entity:

/**
 * @var int
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @ORM\ManyToOne(targetEntity="Session", inversedBy="game")
 * @ORM\JoinColumn(name="session_id")
 */
private $session;

Session Entity:

/**
 * @var int
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @ORM\OneToMany(targetEntity="Game", mappedBy="session")
 */
private $game;

Controller:

/**
 * @param Request $request
 * @return \Symfony\Component\HttpFoundation\Response
 * @Route("/session/new")
 */
public function addnewsessionAction(Request $request)
{
    $session = new Session();

    $form = $this->createForm(SessionType::class, $session);
    $form->handleRequest($request);

    if ($form->isSubmitted())
    {
        $em = $this->getDoctrine()->getManager();
        $em->persist($session);
        $em->flush();

        return $this->redirectToRoute('app_game_addnewsessiongame', array('sessionid' => $session->getId()));
    }

    return $this->render(':session:addsession.html.twig', array(
        'form' => $form->createView(),
    ));
}


/**
 * @param Request $request
 * @return \Symfony\Component\HttpFoundation\Response
 * @Route("/session/{sessionid}/addnewgame")
 */
public function addnewsessiongameAction(Request $request, $sessionid)
{
    $game = new Game();

    $form = $this->createForm(GameType::class, $game, array('sessionid' => $sessionid));
    $form->handleRequest($request);

    if ($form->isSubmitted())
    {
        $em = $this->getDoctrine()->getManager();
        $em->persist($game);
        $em->flush();

        return $this->redirectToRoute('app_game_addnewsessiongame', array('sessionid' => $sessionid));
    }

    return $this->render(':game:addgame.html.twig', array(
        'form' => $form->createView(),
        'sessionid' => $sessionid,
    ));
}

GameType (game inserted correctly when I select the session manually):

$builder
        ->add('session', 'entity', array(
            'class' => 'AppBundle\Entity\Session',
            'query_builder' => function(EntityRepository $er ) use ( $options ) {
                return $er->createQueryBuilder('w');
            },
        ))

GameType (when only one session is given trough the controller):

        $builder
        ->add('session', 'entity', array(
            'class' => 'AppBundle\Entity\Session',
            'query_builder' => function(EntityRepository $er ) use ( $options ) {
                return $er->createQueryBuilder('w')
                    ->where('w.id = ?1')
                    ->setParameter(1, $options['sessionid']);
            },

In case two the select option displays only the given entity, but is saved in db with NULL. Even if I select this only one option again NULL is saved in db.

I want to save the correct session automatically, so the user don't have to select the session. The select form will be displayed:hidden with additional 'attr' => array('class' => 'hidden')

after a night fully of sleep i got the solution. I took the session entity and throw it trough the form into the game entity

Controller:

 /**
 * @param Request $request
 * @return \Symfony\Component\HttpFoundation\Response
 * @Route("/session/{sessionid}/addnewgame")
 */
public function addnewsessiongameAction(Request $request, $sessionid)
{
    $game = new Game();

    $em = $this->getDoctrine()->getManager();
    $mysession = $em->getRepository('AppBundle:Session')->find($sessionid);

    $game->setSession($mysession);

    $form = $this->createForm(GameType::class, $game, array('sessionid' => $sessionid));
    $form->handleRequest($request);

    if ($form->isSubmitted())
    {
        $em = $this->getDoctrine()->getManager();
        $em->persist($game);
        $em->flush();

        return $this->redirectToRoute('app_game_addnewsessiongame', array('sessionid' => $sessionid));
    }

    return $this->render(':game:addgame.html.twig', array(
        'form' => $form->createView(),
        'sessionid' => $sessionid,
    ));
}

GameType:

$builder->add('session','entity', array('class' => 'AppBundle\Entity\Session','attr' => array('class' => 'hidden')))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM