Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access Entity class from Sonata Admin's Admin class?

Let me explain: I have an Entity class Item with a method getName() in it, namespace App\Entity. I have an admin class for it in Sonata Admin, namespace App\Admin, and would like to call that method from within, how to do so?

//Symfony2 Entity
...
class Item
{
    public function getName(){
         return $this->name;
    }
}

...
//Sonata Admin class
class ItemAdmin extends Admin
{
  ...
  protected function configureListFields(ListMapper $listMapper){
     //how to access Item class' getName() method from here?
  }
}

EDIT: This works inside configureListFields(), but what about without find() and if with find() only, then how to automatically get 'id'?

 $item=$this->getConfigurationPool()->getContainer()->get('Doctrine')->getRepository('AppBundle:Item')->find('15');
 echo $item->getName();
like image 354
Muhammed Avatar asked Mar 01 '16 08:03

Muhammed


2 Answers

Simple and easy

$container = $this->getConfigurationPool()->getContainer();
$em = $container->get('doctrine.orm.entity_manager');
like image 94
yakob abada Avatar answered Oct 19 '22 11:10

yakob abada


You have to get EntityManager:

   //Sonata Admin class
class ItemAdmin extends Admin
{
  ...
  protected function configureListFields(ListMapper $listMapper){
    $id = $this->getSubject()->getId();

    $em = $this->modelManager->getEntityManager(YourBundle:Item);
    $item = $em->getRepository('YourBundle:Item')->find($id);
    $item->getName()
    ...
  }
}
like image 4
Anna Adamchuk Avatar answered Oct 19 '22 09:10

Anna Adamchuk