5
votes

I am currently working with Symfony2 and I am getting this ERROR message:

Undefined method 'getDoctrine'. The method name must start with either findBy or findOneBy! 500 Internal Server Error - BadMethodCallException

This is my Entity Class:

 <?php

namespace Gestionresiduos\ResiduoBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
* @ORM\Entity(repositoryClass="ResiduoRepository")
*/

class BodegaContieneResiduo
{


    /**
    * @ORM\Id
    * @ORM\column(type="integer")
    * @ORM\GeneratedValue
    */

    protected $idContiene;

.....

}

This is the Controller's page Action method:

 <?php

namespace Gestionresiduos\ResiduoBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class DefaultController extends Controller
{
    public function portadaAction()
    {
        $em = $this->getDoctrine()->getEntityManager();

        $ofertas= $em->getRepository('ResiduoBundle:BodegaContieneResiduo')->findResiduosAlmacenados();
        return $this->render('ResiduoBundle:Default:index.html.twig');
    }
}

This is my EntityRepository:

    <?php
namespace Gestionresiduos\ResiduoBundle\Entity;

use Doctrine\ORM\EntityRepository;

class ResiduoRepository extends EntityRepository
{

    public function findResiduosAlmacenados()
    {
        $em = $this->getDoctrine()->getEntityManager();
        $consulta = $em->createQuery('SELECT r FROM ResiduoBundle:BodegaContieneResiduo');
        return $consulta->getOneOrNullResult();
    }
}

I also tried all solutions in this post by ScoRpion and this post by K-Alex

So, Where is THE PROBLEM ???

2
Inside of the repository you should be able to access the entity manager like this $this->_em. So you could just use: $this->_em->createQuery()TheFrozenOne

2 Answers

16
votes

In the Repository class, instead of:

$em = $this->getDoctrine()->getEntityManager();

You should use:

$em = $this->getEntityManager();

Reference:

http://www.doctrine-project.org/api/orm/2.2/class-Doctrine.ORM.EntityRepository.html

2
votes

Ok, first: @ORM\Entity(repositoryClass="ResiduoRepository") should contain full namespace. e.g: MyCompany\Namespace\Repository

Second you have a typo or you are calling the wrong repository:

$ofertas= $em->getRepository('ResiduoBundle:BodegaContieneResiduo')->findResiduosAlmacenados()

You are calling BodegaContieneResiduo but you defined repository as ResiduoRepository, you don't call it's classname but repository name.