检查实体参数路由



如何使用以下方法检查元素是否存在:

#[Route('/edit/{id}', name: 'edit')]
public function edit(Category $category): Response
{
//some code
return $this->render('someView.html.twig');
}

与此方法类似:

#[Route('/edit/{id}', name: 'edit')]
public function edit($id, CategoryRepository $categoryRepository): Response
{
$category= $categoryRepository->findOneBy(['id' => $id]);
if (!$category) return $this->redirectToRoute('category_list');
return $this->render('someView.html.twig');
}

您不能,因为ParamConverter为您处理它。如果它找不到对象,那么在生产中就会出现404错误。

如果你绝对想自定义重定向或其他什么,你必须像第二个例子一样手动执行。

在第一个示例中,如果id参数与类别对象不匹配,将自动抛出一个未找到的异常,而在第二个示例中则根据类别手动重定向用户。

最新更新