Search code examples
symfony

Cannot autowire argument $article : Symfony 5


I'm currently facing to this error when I try to get my article page : Cannot autowire argument $article of "App\Controller\HomeController::show()": it references class "App\Entity\Article" but no such service exists.

I just created a very new small symfony 5 application : The code in my controller is :

/**

 * @Route("/show/{id}", name="show")
 */
public function show(Article $article): Response
{
    if(!$article) {
        return $this->redirectToRoute('home');
    }
    
    return $this->render('show/index.html.twig', [
        'article' => $article,
    ]);
}

I am following a tutorial on Udemy and I guess that I did the same thing as the former. Maybe version difference ?


Solution

  • The error you have is saying that it cannot find the auto-wire path to your entity. Using the Symfony installer will automatically configure parts like this for you.

    The main part which auto-wires the Entity to the Dependency Injection layer is through Doctrine configuration and the Symfony ParamConverter found as part of the SensioFrameworkExtraBundle.

    The ParamConverter has a lot of options to be able to convert parameters inside of the @Route into an Entity. Using your example above we see that Symfony will internally call ArticleRepository->findOneById($id) and return the result to your controller.

    EDIT: Removed all mentions of Doctrine configurations. The errors that are displayed when Doctrine is not auto-wiring are different.