Search code examples
phpsymfonycontrollerdoctrineundefined

Undefined method getDoctrine


I am a beginner on Symfony 6 and I am blocked because I have an error message: "Undefined method getDoctrine" with Intelephense

Here is my code:

 #[Route('/recettes', name: 'app_recettes')]

    public function index(int $id): Response
    {
        $em = $this->getDoctrine()->getManager();
        $recette = $em->getRepository(Recettes::class)->findBy(['id' => $id]);

        return $this->render('recettes/index.html.twig', [
            'RecettesController' => 'RecettesController',
        ]);
    }

Solution

  • Your controller should extends AbstractController from use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

    You should not use getDoctrine()->getManager() in symfony 6. If you look into the method from AbstractController you can see:

    trigger_deprecation('symfony/framework-bundle', '5.4', 'Method "%s()" is deprecated, inject an instance of ManagerRegistry in your controller instead.', __METHOD__);
    

    You should just autowire your entity manager in your method or constructor and use it directly.

    private EntityManagerInterface $entityManager;
    
    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->entityManager = $entityManager;
    }
    
    #[Route('/recettes', name: 'app_recettes')]
    public function index(int $id): Response
    {
        $recette = $this->entityManager->getRepository(Recettes::class)->findBy(['id' => $id]);
    
        return $this->render('recettes/index.html.twig', [
            'RecettesController' => 'RecettesController',
        ]);
    }
    

    You could also autowire your RecettesRepository directly instead of the entity manager if you just want to fetch some data.

    I'm guessing that you want to show a specific resource by using its id. You probably want to add something /{id} in your route:

    #[Route('/recettes/{id}', name: 'app_recettes')]