I’m coding a blog with Symfony 5 and I have issues getting the Id from the URL to display comments from my Database.
To sum up : – I have a view “/fiche/{id}” wish displays specific game informations. – People can leave a comment below, the comment goes in Database with a foreign Key named “jeu_id” wish is the game where the comment were posted.
- The goal is to display now all the comments wish were posted on this specific game. I want to display all the comments with foreign key “jeu_id” wish is in the url “/fiche/{id}”.
Here’s the method in my controller :
x
/**
* @Route("/fiche/{id}", name="fiche", methods={"POST", "GET"})
*/
public function fiche($id, Jeux $jeux, Request $request): Response
{
$id = (int)$request->get('id');
$commentaires = $this->getDoctrine()->getRepository(Jeux::class)->find($id);
$commentaire = new Commentaires();
$commentaire->setCreatedAt(new DateTime("NOW"));
$request = Request::createFromGlobals();
$commentaire->setJeu($jeux);
$form = $this->createForm(CommentairesType::class, $commentaire);
$form->handleRequest($request);
//test variable
//dd($id);
dd($commentaire->getJeu($id));
if ($form->isSubmitted() && $form->isValid()) {
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($commentaire);
$entityManager->flush();
return $this->redirectToRoute('liste');
}
return $this->render('main/fiche.html.twig', [
'commentaires' => $commentaires,
'jeux' => $jeux,
'form' => $form->createView(),
]);
}
Here’s the concern variables in entity “Commentaires” :
/**
* @ORMManyToOne(targetEntity=Jeux::class, inversedBy="commentaires")
* @JoinColumn(name="jeu_id", referencedColumnName="id")
* @ORMJoinColumn(nullable=true)
*/
private $jeu;
public function getJeu(): ?Jeux
{
return $this->jeu;
}
public function setJeu($jeu): self
{
$this->jeu = $jeu;
return $this;
}
Here’s the concern variables in entity “Jeux” :
/**
* @ORMOneToMany(targetEntity=Commentaires::class, mappedBy="jeu", orphanRemoval=true)
*/
private $commentaires;
/**
* @return Collection|Commentaires[]
*/
public function getCommentaires(): Collection
{
return $this->commentaires;
}
Advertisement
Answer
I think the right way would be something like this:
/**
* @Route("/fiche/{jeux}",
* name="fiche"
*/
public function fiche(Request $request, Jeux $jeux, EntityManagerInterface $em): Response
{
$form = $this->createForm(CommentaireType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$commentaire = $form->getData();
$commentaire->setCreatedAt(new DateTime("NOW"));
$jeux->addCommentaire($commentaire);
$em->persist($commentaire);
$em->flush();
return $this->redirectToRoute('liste');
}
return $this->render('main/fiche.html.twig', [
'commentaires' => $jeux->getCommentaires(),
'jeux' => $jeux,
'form' => $form->createView(),
]);
}