2017-03-26 2 views
0

안녕하세요. 시간을내어 읽어 주셔서 감사합니다. 영어가 제 첫 번째 언어가 아니므로 어떤 오류라도 용서해 주시기 바랍니다. Symfony 하우투 엔티티를 생성하고 다른 엔티티를 추가 하시겠습니까?

내가 PlayLog에 oneToMany 관계, 게임이 있습니다 현재 내가 프로젝트를 수행하고있어 심포니 3.

에 익숙해이 내가 할 노력하고있어 것입니다. 관계가 설정되어 있고 내 게임에서 날짜 목록을 볼 수 있습니다.

새로운 PlayLog를 만들고 게임과 연결되어 게임을 통해 관련된 모든 PlayLog에 액세스 할 수 있습니다. 뷰는 게임의 ID (log.html.twig)로 표시됩니다

내 질문 : 나는 양식과 날짜 양식 필드 (dateType)와 함께 새로운 PlayLog를 생성하고 그것을 추가하려면 어떻게 기존 게임?

업데이트 : 지금이 오류가 현재 코드 :

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

이 내 코드입니다 :

--- 개체/Game.php

<?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->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->id; 
    } 

    /** 
    * Set name 
    * 
    * @param string $name 
    * 
    * @return Game 
    */ 
    public function setName($name) 
    { 
     $this->name = $name; 

     return $this; 
    } 

    /** 
    * Get name 
    * 
    * @return string 
    */ 
    public function getName() 
    { 
     return $this->name; 
    } 

    /** 
    * @return mixed 
    */ 
    public function getType() 
    { 
     return $this->type; 
    } 

    /** 
    * @ORM\Column (options={"default" = none}) 
    * @param mixed $type 
    */ 
    public function setType($type) 
    { 
     $this->type = $type; 
    } 


    /** 
    * @return mixed 
    */ 
    public function getPlaylogs() 
    { 
     return $this->playlogs; 
    } 

    /** 
    * @param mixed $playlogs 
    */ 
    public function setPlaylogs($playlogs) 
    { 
     $this->playlogs = $playlogs; 
    } 

    public function addPlayLog(PlayLog $playlog) 
    { 
     $this->playlog->add($playlog); 
     $playlog->setPlayLogs($this); 
    } 

} 

--- 엔티티/PlayLog.php

<?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->id; 
    } 

    /** 
    * Set date 
    * 
    * @param \DateTime $date 
    * 
    * @return PlayLog 
    */ 
    public function setDate($date) 
    { 
     $this->date = $date; 

     return $this; 
    } 

    /** 
    * Get date 
    * 
    * @return \DateTime 
    */ 
    public function getDate() 
    { 
     return $this->date; 
    } 

    /** 
    * Set gameId 
    * 
    * @param integer $gameId 
    * 
    * @return PlayLog 
    */ 
    public function setGameId($gameId) 
    { 
     $this->gameId = $gameId; 

     return $this; 
    } 

    /** 
    * Get gameId 
    * 
    * @return int 
    */ 
    public function getGameId() 
    { 
     return $this->gameId; 
    } 


    public function addGame(Game $game) 
    { 
     $this->games->add($game); 
     $game->setType($this); 
    } 
    public function removeGame(Game $game) 
    { 
     $this->games->removeElement($game); 
    } 



} 

--- GameController.php

<?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->getDoctrine()->getManager(); 
//  $games = $em->getRepository('AppBundle:Game')->findAll(); 
     $dql = "SELECT game FROM AppBundle:Game game JOIN game.type type ORDER BY game.name"; 
     $query = $em->createQuery($dql); 
     /* 
     * @var $paginator \Knp\Component\Pager\Paginator 
     */ 
     $paginator = $this->get('knp_paginator'); 
     $result = $paginator->paginate(
      $query, 
      $request->query->getInt('page', 1), 
      $request->query->getInt('limit', 25) 
     ); 
//  dump(get_class($paginator)); 

     return $this->render('game/index.html.twig', array(
      'games' => $result, 
      'max_limit_error' => 25 
     )); 
    } 

    /** 
    * Creates a new game entity. 
    * 
    * @Route("/new", name="game_new") 
    * @Method({"GET", "POST"}) 
    */ 
    public function newAction(Request $request) 
    { 

     $game = new Game(); 

     $form = $this->createForm('AppBundle\Form\GameType', $game); 
     $form->handleRequest($request); 

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

      return $this->redirectToRoute('game_show', array('id' => $game->getId())); 
     } 

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

    /** 
    * Finds and displays a game entity. 
    * 
    * @Route("/{id}", name="game_show") 
    * @Method("GET") 
    */ 
    public function showAction(Game $game) 
    { 
     $deleteForm = $this->createDeleteForm($game); 


     return $this->render('game/show.html.twig', array(
      'game' => $game, 
      'delete_form' => $deleteForm->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->createDeleteForm($game); 
     $editForm = $this->createForm('AppBundle\Form\GameType', $game); 
     $editForm->handleRequest($request); 

     if ($editForm->isSubmitted() && $editForm->isValid()) { 
      $this->getDoctrine()->getManager()->flush(); 

      return $this->redirectToRoute('game_show', array('id' => $game->getId())); 
     } 

     return $this->render('game/edit.html.twig', array(
      'game' => $game, 
      'edit_form' => $editForm->createView(), 
      'delete_form' => $deleteForm->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->createForm(GameType::class, $game); 
     $form->handleRequest($request); 
     if($form->isSubmitted() && $form->isValid()) { 

      //Save playLog 
      $em = $this->getDoctrine()->getManager(); 
      $em->persist($playlog); 
      $em->flush(); 

     } 
     // Render/return view incl. formulier. 
     return $this->render('game/log.html.twig', array(
      'game' => $game, 
      'form' => $form->createView(), 
     )); 
    } 

    /** 
    * Deletes a game entity. 
    * 
    * @Route("/{id}", name="game_delete") 
    * @Method("DELETE") 
    */ 
    public function deleteAction(Request $request, Game $game) 
    { 
     $form = $this->createDeleteForm($game); 
     $form->handleRequest($request); 

     if ($form->isSubmitted() && $form->isValid()) { 
      $em = $this->getDoctrine()->getManager(); 
      $em->remove($game); 
      $em->flush($game); 
     } 

     return $this->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->createFormBuilder() 
      ->setAction($this->generateUrl('game_delete', array('id' => $game->getId()))) 
      ->setMethod('DELETE') 
      ->getForm() 
     ; 
    } 
} 

--- PlayLogController.php

<?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->getDoctrine()->getManager(); 

     $playLogs = $em->getRepository('AppBundle:PlayLog')->findAll(); 

     return $this->render('playlog/index.html.twig', array(
      'playLogs' => $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->createForm('AppBundle\Form\PlayLogType', $playlog); 
     $form->handleRequest($request); 

     $playlog->setGameId($gameId); 
     echo $playlog->getGameId()."!"; 
     if ($form->isSubmitted() && $form->isValid()) { 
      $em = $this->getDoctrine()->getManager(); 
      $em->persist($playlog); 
      $em->flush(); 
//   return $this->redirectToRoute('game_show', array('id' => $gameId)); 
     } 

     return $this->render('playlog/new.html.twig', array(
      'playLog' => $playlog, 
      'form' => $form->createView(), 
     )); 
    } 
     return $this->render('playlog/new.html.twig', array(
      'playLog' => $playLog, 
      'form' => $form->createView(), 
     )); 
    } 

    /** 
    * Finds and displays a playLog entity. 
    * 
    * @Route("/{id}", name="playlog_show") 
    * @Method("GET") 
    */ 
    public function showAction(PlayLog $playLog) 
    { 
     $deleteForm = $this->createDeleteForm($playLog); 

     return $this->render('playlog/show.html.twig', array(
      'playLog' => $playLog, 
      'delete_form' => $deleteForm->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->createDeleteForm($playLog); 
     $editForm = $this->createForm('AppBundle\Form\PlayLogType', $playLog); 
     $editForm->handleRequest($request); 

     if ($editForm->isSubmitted() && $editForm->isValid()) { 
      $this->getDoctrine()->getManager()->flush(); 

      return $this->redirectToRoute('playlog_edit', array('id' => $playLog->getId())); 
     } 

     return $this->render('playlog/edit.html.twig', array(
      'playLog' => $playLog, 
      'edit_form' => $editForm->createView(), 
      'delete_form' => $deleteForm->createView(), 
     )); 
    } 

    /** 
    * Deletes a playLog entity. 
    * 
    * @Route("/{id}", name="playlog_delete") 
    * @Method("DELETE") 
    */ 
    public function deleteAction(Request $request, PlayLog $playLog) 
    { 
     $form = $this->createDeleteForm($playLog); 
     $form->handleRequest($request); 

     if ($form->isSubmitted() && $form->isValid()) { 
      $em = $this->getDoctrine()->getManager(); 
      $em->remove($playLog); 
      $em->flush(); 
     } 

     return $this->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->createFormBuilder() 
      ->setAction($this->generateUrl('playlog_delete', array('id' => $playLog->getId()))) 
      ->setMethod('DELETE') 
      ->getForm() 
     ; 
    } 
} 

--- 게임/log.html.twig

{% extends 'base.html.twig' %} 
{% block content %} 
    Adding log for {{ game.name }} 
    {{ form_widget(form.playlogs) }} 

    <input type="submit" value="Create" class="btn btn-default pull-left" /> 
{% endblock content %} 

--- PlayLogType.php

<?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->add('date'); 
    } 

    /** 
    * {@inheritdoc} 
    */ 
    public function configureOptions(OptionsResolver $resolver) 
    { 
     $resolver->setDefaults(array(
      'data_class' => PlayLog::class 
     )); 
    } 

    /** 
    * {@inheritdoc} 
    */ 
    public function getBlockPrefix() 
    { 
     return 'appbundle_playlog'; 
    } 


} 

--- GameType.php

이것이 당신이 찾고있는 해답 ..이 경우 6,
<?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 
       ->add('name', TextType::class, [ 
        'attr' => [ 
         'class' => 'form-control', 
        ], 
       ]); 
      $builder 
       ->add('type', EntityType::class, [ 
        'class' => 'AppBundle:Type', 
        'choice_label' => function ($type) { 
         return $type->getName(); 
        }, 
        'multiple' => false, 
        'expanded' => false, 
        'attr' => [ 
         'class' => 'form-control', 
        ], 

       ]); 

      $builder->add('playlogs', CollectionType::class, array(
       'entry_type' => PlayLogType::class, 
       'label' => false 
      )); 


     } 

     /** 
     * {@inheritdoc} 
     */ 
     public function configureOptions(OptionsResolver $resolver) 
     { 
      $resolver->setDefaults(array(
       'data_class' => 'AppBundle\Entity\Game' 
      )); 
     } 

     /** 
     * {@inheritdoc} 
     */ 
     public function getBlockPrefix() 
     { 
      return 'appbundle_game'; 
     } 


    } 

답변

0

나는 그것을 알아 냈다. 나는 단지 ID ($ gameId)로 유지하려했지만 전체 Game 객체를 기대했다. (1) 그래서 내가 먼저 ID와 실제 저장소 개체를 가져했고 그 후 나는이 객체 지속될 수 :이 오류 코드와

public function newAction(Request $request, $gameId) 
    { 
     $playlog = new PlayLog(); 
     $em = $this->getDoctrine()->getManager(); 
     // (1) Get Game object with given gameId: 
     $game = $em ->getRepository(Game::class)->find($gameId); 

     //Set the Game object 
     $playlog->setGame($game); 
     $form = $this->createForm('AppBundle\Form\PlayLogType', $playlog); 
     $form->handleRequest($request); 

     if ($form->isSubmitted() && $form->isValid()) { 
      /* @var $playLog PlayLog */ 
      $playlog = $form->getData(); 

      $em->persist($playlog); 
      $em->flush(); 
     } 

     return $this->render('playlog/new.html.twig', array(
      'playLog' => $playlog, 
      'form' => $form->createView(), 
     )); 
    } 
0

확실하지

당신이 경로에 게임 ID를 추가 할 수 있도록 당신은 Playlog 컨트롤러에 조금 당신의 newAction 자신의 경로 주석을 형식에 설정을 몇 수

/** 
* Creates a new playLog entity. 
* 
* @Route("/{gameId}/new", name="playlog_new") 
* @Method({"GET", "POST"}) 
*/ 
public function newAction(Request $request, $gameId) 
{ 
    $em = $this->getDoctrine()->getManager(); 

    $game = $em->getRepository('AppBundle:Game')->find($gameId); 

    if(null === $game) { 
     throw $this->createNotFoundException('The game with id ' . $gameId . ' does not exist.'); 
    } 

    $playLog = new Playlog(); 
    $playLog->SetGame($game); 
    $form = $this->createForm('AppBundle\Form\PlayLogType', $playLog); 
    $form->handleRequest($request); 

    if ($form->isSubmitted() && $form->isValid()) { 
     $em->persist($playLog); 
     $em->flush($playLog); 

     return $this->redirectToRoute('playlog_show', array('id' => $playLog->getId())); 
    } 

    return $this->render('playlog/new.html.twig', array(
     'playLog' => $playLog, 
     'form' => $form->createView(), 
    )); 
} 
+0

을 : play_log INTO INSERT '실행하는 동안 예외가 발생했습니다 (date, game_id) VALUES (?,?) 'with params [ "2017-03-04", null] : SQLSTATE [23000] : 무결성 제약 조건 위반 : 1048'game_id '열은 null 일 수 없습니다. – Ducky

+0

이것은 PlayLog 엔터티와 관련이 있다고 생각합니다. 모든 메소드와 $ game_id 속성도 삭제하고 cli 명령으로 메소드를 다시 빌드하십시오. bin/console doctrine : generate : entities AppBundle : PlayLog 그리고 물론 데이터베이스 스키마도 업데이트하십시오 : bin/console doctrine : schema : update --force –

+0

아, 너무 가까이 있어요 : $ playlog-> getGameId()는 이제 ID를 반환합니다. 즉, 내가 액세스 할 수 있다는 의미입니다. 내 코드를 업데이트했습니다. – Ducky