Symfony 4 - 如何在表单提交后为重定向中的路由设置实体 ID

Symfony 4 - How to set entity id for route in redirect after form submit

构建 Symfony 4.1 应用程序。在我的 ProfileController 中 ...

我有一个 booking_new 方法和表单来创建新预订:

/**
 * @Route("/profile/booking/new", name="profile_booking_new")
 */
public function booking_new(EntityManagerInterface $em, Request $request)
{

    $form = $this->createForm(BookingFormType::class);

    $form->handleRequest($request);
    if ($form->isSubmitted() && $form->isValid()) {
        /** @var @var Booking $booking */
        $booking = $form->getData();
        $booking->setUser($this->getUser());

        $em->persist($booking);
        $em->flush();

        return $this->redirectToRoute('profile_booking_show');

    }

    return $this->render('profile/bookings/booking_new.html.twig',[
        'bookingForm' => $form->createView()
    ]);
}

然后我有一个 booking_show 方法来呈现路由设置为预订 ID 的单个预订页面:

/**
 * @Route("/profile/booking/{id}", name="profile_booking_show")
 */
public function booking_show(BookingRepository $bookingRepo, $id)
{
    /** @var Booking $booking */
    $booking = $bookingRepo->findOneBy(['id' => $id]);

    if (!$booking) {
        throw $this->createNotFoundException(sprintf('There is no booking for id "%s"', $id));
    }

    return $this->render('profile/bookings/booking_show.html.twig', [
        'booking' => $booking,
    ]);
}

创建预订后,我想使用正确的 ID 将用户重定向到节目预订视图。

运行 服务器并收到此错误...

ERROR: Some mandatory parameters are missing ("id") to generate a URL for route "profile_booking_show".

我明白这个错误,但我该如何解决?如何设置刚刚创建的预订的id而不需要查询id?

docs 所述,您必须添加一个参数数组作为第二个参数

return $this->redirectToRoute('profile_booking_show', ['id'=>$id]);

保存并刷新新实体后,您可以像这样使用它:

 $em->persist($booking);
 $em->flush();

 return $this->redirectToRoute('profile_booking_show', ['id' => $bookig->getId()]);