I'm new in symfony2.I created a repository class when I created an entity class through command line.But I couldn't access my custom functions in that repository class. how to create custom repository class in symfony2? Can anybody give me a step by step explanation from scratch with some sample code?
Below is my repository class
namespace Mypro\symBundle\Entity;
use Doctrine\ORM\EntityRepository;
/**
* RegisterRepository
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class RegisterRepository extends EntityRepository
{
public function findAllOrderedByName()
{
return $this->getEntityManager()
->createQuery('SELECT p FROM symBundle:Register p ORDER BY p.name ASC')
->getResult();
}
}
I called in my controller like this way
$em = $this->getDoctrine()->getEntityManager();
$pro = $em->getRepository('symBundle:Register')
->findAllOrderedByName();
I got the below error
Undefined method 'findAllOrderedByName'. The method name must start with either findBy or findOneBy!
Do I have any mistake in my code ? Any mistake in creating repository class? did i need to use any class.
I think you just forgot to register this repository in your entity. You just have to add in your entity configuration file the repository class.
In src/Mypro/symBundle/Resources/config/doctrine/Register.orm.yml:
Mypro\symBundle\Entity\Register:
type: entity
repositoryClass: Mypro\symBundle\Entity\RegisterRepository
Don't forget to clear your cache after this change, just in case.
And if you're using Annotations (instead of yml config) then instead of the above, add something like:
/**
* @ORM\Entity(repositoryClass="Mypro\symBundle\Entity\RegisterRepository")
*/
to your Entity class to register the repository
The manual has a nice step by step guide ... http://symfony.com/doc/current/book/doctrine.html#custom-repository-classes
I too lost a lot of time when I got into this mess of configuration. I was configuring the repository class in my Entity as annotation mapping. The mapping was there but still the repository was not associated with the entity. When I moved the annotation mapping i.e. @ORM\Entity(repositoryClass="Acme\DemoBundle\Entity\UserRepository"), to the last line, it worked.
/*
* User
*
* @ORM\Table()
* @ORM\Entity(repositoryClass="Acme\DemoBundle\Entity\UserRepository")
*/
class User
{
...
}`
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With