How can I use doctrine find method in repository - php

This code is working fine in controller
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository('AcmeUserBundle:Child')->find($id);
Now I have custom Repository class
I want to know that how can use that in there
function getUser()
{
$em = $this->getEntityManager();
$entity = $em->getRepository('AcmeUserBundle:Child')->find($id);
}
Do I still need to use getRepository in Repository as well or not?

If the method is in Repository class, then you could just use $this.
$enity = $this->find($id);

Related

symfony2 method undefined in EntityRepository

i want create a request from my EntityRepository so this is my code:
<?php
namespace zhr\myprojectBundle\Entity;
use Doctrine\ORM\EntityRepository;
/**
* myprojectdbEntityRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class myprojectdbEntityRepository extends EntityRepository
{
public function getAll()
{
$qb = $this->createQueryBuilder('s');
$query = $qb;
$result = $qb->getQuery()->execute();
}
}
i want use it in my controller file so this is my code:
public function searchusersAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$repository = $em->getRepository('myprojectBundle:User');
$utilisateur = $repository->getAll();
var_dump($utilisateur); die();
//return $this->render('mypageBundle:Admin:adminindex.html.twig', array('sheet'=>$utilisateur));
}
i get a error:
Undefined method 'getAll'. The method name must start with either findBy or findOneBy!
??? normaly all methode in repository file must be defined in my controller file no ?
thanks first guys
You have to use getResult() to return a result as follow:
public function getAll()
{
return $this->createQueryBuilder('s')->getQuery()->getResult();
}
But you really don't need this kind of function since EntityRepository class already has findAll() function to get all rows from an entity:
$em = $this->getDoctrine()->getManager();
$rows = $em->getRepository('myprojectBundle:User')->findAll();
I suggest you to check documentation for QueryBuilder and EntityRepository api.

Symfony 3.0: Reuse entity in repository

On my Symfony 3.0 project I have a Entity named ImageGroups and a repository I made ImageGroupsRepository that Use ImageGroups entity. I also made an Images entity with a ImagesRepository
In ImageGroupsRepository I have a method named getUserImageGroups and on ImagesRepository I have a method named add.
What I want to ask is How to use the getUserImageGroups method from ImageGroupsRepository into add from ImagesRepository?
The answer given by A.L is correct, I just wanted to offer an alternative method to access the entity manager without having to call the function again, via $this->_em:
class ImagesRepository extends EntityRepository
{
public function add()
{
$imagesGroups = $this->_em
->getRepository('AcmeBundle:ImageGroups')
->getUserImageGroups();
// …
}
}
If you look at the documentation for EntityRepository you'll see that the getEntityManager() function simply returns the protected $_em member of the EntityRepository class.
In your repository, you can get the entity manager with $this->getEntityManager(), this allow to call getRepository() in order to get another repository:
class ImagesRepository extends EntityRepository
{
public function add()
{
$em = $this->getEntityManager();
$imagesGroups = $em
->getRepository('AcmeBundle:ImageGroups')
->getUserImageGroups();
// …
}
}

Symfony2 and Doctrine - Generate code on insertion

Using Symfon2.0 and Doctrine, I am trying to do the following:
Insert a new row in the database
in the moment of inserting, automatically generate a code and also insert it.
That code is related to the ID of the table. Something like <something>/row_id
How can I easily do this?
I've been trying Doctrine Livecycle callbacks. But:
PrePersist still doesn't have the ID.
PostPersist have the ID, but somehow the insertion has already been done and, although I can set any property from the Entity, I don't know how to make it to be persisted "again" to the database.
Any clue overthere?
Any other way to do it properly?
In your create controller:
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
$entity->setCode($code);
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('entity_show'
,array('id' => $entity->getId())));
}
The second block ($entity->setCode...) is what you need to add and will need to be customized to suit your purposes
Alternatively, you can use Listeners:
<?php
namespace ormed\ormedBundle\Listener;
use Doctrine\ORM\Event\OnFlushEventArgs; use
Symfony\Component\DependencyInjection\Container;
class LastModifiedListener {
private $container;
public function __construct(Container $container){$this->container = $container;}
public function onFlush(OnFlushEventArgs $eventArgs)
{
$entityManager = $eventArgs->getEntityManager();
$unitOfWork = $entityManager->getUnitOfWork();
foreach ($unitOfWork->getScheduledEntityInsertions() AS $entity) {
$entity->setCode( $code );
$entityManager->persist($entity);
$classMetadata = $entityManager->getClassMetadata(get_class($entity));
$unitOfWork->recomputeSingleEntityChangeSet($classMetadata, $entity);
} } }

How can i put where clause in symfony repository query in controller

Initially I am using this
$entities = $em->getRepository('AcmePanduBundle:Checklist')->findAll();
Now I want that if pid variable is present then it should filter the query with something
$entities = $em->getRepository('AcmePanduBundle:Checklist')->findAll('where pid=1')
and if its not present then findAll should work.
Can I do that in controller or do I have to make a custom function in repository class?
Of course you can do that in the controller:
$entities = (isset($pid))
? $em->getRepository('AcmePanduBundle:Checklist')->findByPid($pid)
: $em->getRepository('AcmePanduBundle:Checklist')->findAll();
However, this is the type of thing that custom repositories were made for. If you plan on replicating this logic in more than one place, I'd definitely create one.
It would look something like:
// src/Acme/PanduBundle/Repository/ChecklistRepository.php
namespace Acme\PanduBundle\Repository;
use Doctrine\ORM\EntityRepository;
class ChecklistRepository extends EntityRepository
{
public function findAllWithOptionalPid($pid = null)
{
if($pid)
return $this->findByPid($pid);
return $this->findAll();
}
}
...and don't forget to reference this repository in your Doctrine configuration. Don't know what method you're using for configuration (xml, yml, annotations), but here's the documentation for that: http://symfony.com/doc/current/book/doctrine.html#custom-repository-classes
Once that's done, any controller calling $em->getRepository('AcmePanduBundle:Checklist')->findAllWithOptionalPid($pid); will work as you expect it to, with or without the $pid variable.
Use findBy or dynamic methods like "findByPid"
$repository = $em->getRepository('AcmePanduBundle:Checklist');
if ($pid) {
$entities = $repository->findBy(array('pid' => $pid));
// or: $entities = $repository->findByPid($pid);
} else {
$entities = $repository->findAll();
}

Call repository method from entity

Is it possible to call repository method on entity?
I mean something like this
$article = $em->getRepository('Entities\Articles')->findOneBy(array('id' => $articleId));
$category = $em->getRepository('Entities\Categories')->findOneBy(array('id' => 86));
$article->addArticleToCategory($category);
Where addArticleToCategory is method in repository (just an example code)
public function addArticleToCategory($category){
$categoryArticles = new CategoryArticles();
$categoryArticles->setArticle(!!/** This is where I want to have my variable $article from this method call **/!!);
$categoryArticles->setCategory($category);
$this->getEntityManager()->persist($categoryArticles);
$this->getEntityManager()->flush();
}
What is the best way to do it?
Also I want to know is it a good practice to put custom set/create methods in repository?
By definition you can't call a method of your repository class from an entity object... This is basic object-oriented programming.
I think you should create addArticle function in the Category entity, something like this:
function addArticle($article)
{
$this->articles[] = $article;
$article->setCategory($this);
}
And then you do
$article = $em->getRepository('Entities\Articles')->findOneBy(array('id' => $articleId));
$category = $em->getRepository('Entities\Categories')->findOneBy(array('id' => 86));
$category->addArticle($article);
$em->persist($category);
$em->flush();
If the cascades are correctly configured, this will work
You can write your own repository manager and create a method for your needs.
http://docs.doctrine-project.org/en/2.0.x/reference/working-with-objects.html#custom-repositories

Categories