Reputation: 11
I want to redirect users to a 404 page.
My problem is that if the slug does not exist I get an error:
App\Entity\Article object not found by the @ParamConverter annotation.
Unfortunately I can't find a way to get the NULL for the condition.
/**
* @Route("/rubriques/{slugCategory}/{slug}", name="articleSingle")
*/
public function show(Article $article, String $slug): Response
{
$article = $this->repoArticle->findOneBy(['slug' => $slug]);
dd($article);
if (!$article) {
return $this->redirectToRoute('404error');
}
return $this->render("show/index.html.twig", [
'article' => $article,
]);
}
Upvotes: 1
Views: 1360
Reputation: 30763
Why dont you use this:
If the field in Article is slug
you can use it directly:
/**
* @Route("/rubriques/{slugCategory}/{slug}", name="articleSingle")
*/
public function show(Article $article): Response
{
...
}
If the field in Article is different:
/**
* @Route("/rubriques/{slugCategory}/{slug}", name="articleSingle")
* @Entity("article", expr="repository.findOneBySlug(slug)")
*/
public function show(Article $article): Response
{
...
}
where findOneBySlug has to be adepted to the correct method in the repository
see https://symfony.com/doc/current/bundles/SensioFrameworkExtraBundle/annotations/converters.html#fetch-via-an-expression
Upvotes: 0
Reputation: 103
You don't need to set "Article" as your controller dependency as you don't want to use the DoctrineParamConverter to automatically find the object for you. So you should change
public function show(Article $article, String $slug): Response
{
...
}
To
public function show(string $slug): Response
{
...
}
That way, you will be able to manually find the article corresponding to the passed slug and if there is no result, you will be able to redirect the user to a 404 page.
Upvotes: 1