I have an error on a symfony 3.4 project. I'm trying to manage the display of a notification in the menu of my application. So I created a CustomController which extends Controller.
Then I made all my other controllers inherit from CustomController.
But when I make a call to getDoctrine() to reach a repository I get the following error:
"Call to a member function has() on null"
Here is my CustomController:
<?php
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class CustomController extends Controller
{
public $data = [];
protected $em;
public function __construct()
{
$this->em = $this->getDoctrine()->getManager();
$countAttente = $this->em->getRepository('AppBundle:Commandes')->tailleEnAttente("En attente");
$this->data['countAttente'] = $countAttente;
}
}
I tried to pass the controller as a service in service.yml but it did not change anything
AppBundle\Controller\CustomController:
class: AppBundle\Controller\CustomController
arguments: ["@doctrine.orm.entity_manager"]
calls:
- [setContainer, ["@service_container"]]
I found many similar topics on this type of error but none of them allowed me to skip this error
Any help is welcome
CodePudding user response:
Autowire your EntityManager directly inside your constructor:
use Doctrine\ORM\EntityManagerInterface;
private $em;
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
Or if you need a specific repository, and autowired is set up with the default configuration you can do the same as well with the repository:
private $repository;
public function __construct(CommandesRepository $repository)
{
$this->repository = $repository;
}