8

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();
Muhammed
  • 1,592
  • 1
  • 10
  • 18
  • Can you explain what you want to do ? Actually in `configureListFields` there is not an Item instance already selected by the admin , you have to use `ListMapper` methods. – LFI Mar 01 '16 at 08:29
  • I want to do exactly what I wrote there, my Entity has a method, and I want to access it from inside configureListFields(). If there is no way to do this, It would be good to know that. – Muhammed Mar 01 '16 at 08:33
  • 1
    This function goals is to configure a list display, there is no `Item` selected by the `Admin`, no `id` selected, that's not the right place to do this. – LFI Mar 01 '16 at 09:28
  • @MuhammedM. you need elaborate more what you want to achieve ? i mean what you will do with `getName()` in `configureListFields()` function, what is the purpose behind that ? – M Khalid Junaid Mar 02 '16 at 17:28

2 Answers2

8

Simple and easy

$container = $this->getConfigurationPool()->getContainer();
$em = $container->get('doctrine.orm.entity_manager');
cezar
  • 11,616
  • 6
  • 48
  • 84
yakob abada
  • 1,101
  • 14
  • 20
5

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()
    ...
  }
}
Anna Adamchuk
  • 718
  • 4
  • 16