【问题标题】:Symfony 4 - How to set entity id for route in redirect after form submitSymfony 4 - 如何在表单提交后为重定向中的路由设置实体 ID
【发布时间】:2018-12-13 08:47:38
【问题描述】:

构建 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".

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

【问题讨论】:

    标签: symfony doctrine-orm symfony4


    【解决方案1】:

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

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

    【讨论】:

    • @Etshy 谢谢你们,每个答案都很有帮助。
    【解决方案2】:

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

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

    【讨论】:

    • 好的,我试试。 PS 是重定向到 booking_show 页面还是 bookings_list 页面的最佳做法?还是取决于开发者的偏好?
    • 我认为没有最佳实践。这取决于开发人员/客户的偏好。 @G1.3 这只是一个例子,他当然需要采取$booking->getId() 或任何get id 方法。
    • @Etshy 好的。我认为问题的阻碍点是 id 检索 ;)
    • 所以我将 $booking->getId() 直接放在 flush() 之后?
    猜你喜欢
    • 2020-06-17
    • 2023-04-03
    • 2018-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-12
    • 2021-10-02
    相关资源
    最近更新 更多