[英]How do I get Id in the URL to display comments with Symfony 5?
I'm coding a blog with Symfony 5 and I have issues getting the Id from the URL to display comments from my Database.我正在使用 Symfony 5 编写博客,但在从 URL 获取 Id 以显示来自我的数据库的评论时遇到问题。
To sum up: - I have a view "/fiche/{id}" wish displays specific game informations.总结一下: - 我有一个视图“/fiche/{id}”希望显示特定的游戏信息。 - 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.
- 人们可以在下面发表评论,评论进入数据库,带有名为“jeu_id”的外键希望是发布评论的游戏。
Here's the method in my controller:这是我的 controller 中的方法:
/**
* @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":这是实体“评论家”中的关注变量:
/**
* @ORM\ManyToOne(targetEntity=Jeux::class, inversedBy="commentaires")
* @JoinColumn(name="jeu_id", referencedColumnName="id")
* @ORM\JoinColumn(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":这是实体“Jeux”中的关注变量:
/**
* @ORM\OneToMany(targetEntity=Commentaires::class, mappedBy="jeu", orphanRemoval=true)
*/
private $commentaires;
/**
* @return Collection|Commentaires[]
*/
public function getCommentaires(): Collection
{
return $this->commentaires;
}
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(),
]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.