Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

symfony

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);
    }
}
like image 847
Jiew Meng Avatar asked May 07 '12 10:05

Jiew Meng


1 Answers

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.

like image 61
Cerad Avatar answered Oct 19 '22 10:10

Cerad