No Entity Manager in Custom Class and ContextErrorException

偶尔善良 提交于 2019-12-20 01:46:48

问题


I'm trying to create custom Form in Sonata-Admin and I want to get data from database to choices box. When I'm trying to get data via getEntityManager() I got error

No entity manager defined for class \Admin\AdminBundle\Entity\Category

I tried to add entity manager to first argument in service.yml [code below]

services:
  sonata.admin.category:
    class: Admin\AdminBundle\Admin\Category
    tags:
        - {name: sonata.admin, manager_type: orm, group: "Content", label: "Kategoria"}
    arguments:
        - @doctrine.orm.default_entity_manager
        - Admin\AdminBundle\Entity\Category
        - ~
    calls:
        - [ setTranslationDomain, [AdminAdminBundle]]

After i Add default entity manager I'm having error:

ContextErrorException in RoutesCache.php line 47:
Warning: md5() expects parameter 1 to be string, object given

I'm also adding my ConfigureFormFields() function:

protected function configureFormFields(FormMapper $formMapper){

$em = $this->modelManager->getEntityManager('\Admin\AdminBundle\Entity\Category');

$query = $em->createQueryBuilder('c')
    ->select('c')
    ->from('AdminBundle:Category', 'c')
    ->where('c.parent IS NOT NULL')
    ->orderBy('c.root, c.lft', 'ASC');


$formMapper
    ->add ('name', 'text', array('label' => 'Nazwa Kategorii'))
    ->add ('alias', 'text', array('label' => 'Alias'))
    ->add('parent_id', 'sonata_type_model', array(
        'required' => true,
        'query' => $query
    ));

Can somebody help me fix that error ? Thanks for answers,

best regards !


回答1:


You get error because add manager in wrong place. First argument of admin service should be set as the admin service’s code (defaults to the service’s name).

Admin class pharse this string and build some logic based on. You put there manager so you get error.

If you want to add something to your admin class you can simply add as fourth argument (or fifth, sixth ....) like:

 services:
   sonata.admin.category:
    class: Admin\AdminBundle\Admin\Category
    tags:
         - {name: sonata.admin, manager_type: orm, group: "Content", label: "Kategoria"}
     arguments:
         - ~ 
         - Admin\AdminBundle\Entity\Category
         - ~
         - @doctrine.orm.default_entity_manager
calls:
    - [ setTranslationDomain, [AdminAdminBundle]]

And then in your admin class you have to update override constructor, like :

 public function __construct($code, $class, $baseControllerName, $yourManager)
 {
     parent::_construct($code, $class, $baseControllerName);
     $this->yourManager = $yourManager
 }


来源:https://stackoverflow.com/questions/28330036/no-entity-manager-in-custom-class-and-contexterrorexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!