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

Tim*_*URA 0 symfony doctrine-orm symfony4

构建 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()
    ]);
}
Run Code Online (Sandbox Code Playgroud)

然后我有一个 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,
    ]);
}
Run Code Online (Sandbox Code Playgroud)

创建预订后,我想将用户重定向到具有正确 ID 的显示预订视图。

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

ERROR: Some mandatory parameters are missing ("id") to generate a URL for route "profile_booking_show".
Run Code Online (Sandbox Code Playgroud)

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

G1.*_*1.3 6

一旦新实体被持久化和刷新,你可以像这样使用它:

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

 return $this->redirectToRoute('profile_booking_show', ['id' => $bookig->getId()]);
Run Code Online (Sandbox Code Playgroud)