"Call to a member function has() on a non-object" from Symfony 2 Controller

symfony

Solution

The Symfony 2 controller has no __construct method so while calling parent constructors is not a bad idea, it's not going to help.

The problem is that the container gets injected after __construct so trying to get your doctrine entity manager in the constructor will simply not work. I know it's a bit counter intuitive but get the manager in your action methods.

And I'm assuming your Project::NAME class constant has something like 'ProjectBundle:Project' in it.

Problem

I am getting an error `Fatal error: Call to a member function has() on a non-object in /labs/Projects/What2Do/vendor/symfony/src/Symfony/Bundle/FrameworkBundle/Controller/Controller.php on line 161` Am not exactly sure how to debug this. The error is in a Symfony 2 file, not mine ... my controller looks like below. I am running the `indexAction` ``` <?php class ProjectsController extends Controller { /** * @var EntityManager */ protected $em; public function __construct() { $this->em = $this->getDoctrine()->getEntityManager(); } /** * @Route("/") * @Route("/projects", name="listProjects") * @Template() */ public function indexAction() { $projects = $this->em->getRepository(Project::NAME)->findAll(); return array('projects' => $projects); } /** * @Route("/projects/{projId}", name="viewProject") * @Template() */ public function viewAction($projId) { // retrieve project $proj = $this->em->getRepository(Project::NAME)->findOneById($projId); if ($proj == null) throw $this->createNotFoundException ('Invalid project'); return array('proj' => $proj); } } ```

Original source