Search code examples
apidoctrinesonata-admin

How to implement custom model manager in sonata admin


I have a entity in my symfony/sonata application which is not persisted via doctrine orm. Instead i would like to fill the data for these entities on demand by calling an api ... How can i connect this custom managed entity with my existing model which is managed by doctrine orm? Is there a way to exchange the doctrine managing part with my custom api calls? I know there are some repository functions like findAll() findBy() and so on ... is the solution to overwrite this functions?

Another approaches?

Thanks


Solution

  • I had a similar use case. I ended up with a solution which is roughly the following.

    1) Create a custom ModelManager class. In my case I extended the one provided for Doctrine (Sonata\DoctrineORMAdminBundle\Model\ModelManager), but you can also directly implement Sonata\AdminBundle\Model\ModelManagerInterface. Override the methdods you need to change (e.g. create(), update(), delete()).

    # MyCustomModelManager.php
    
    namespace AppBundle\Admin;
    
    use Sonata\DoctrineORMAdminBundle\Model\ModelManager;
    
    class MyCustomModelManager extends ModelManager {
    
        public function create($object){ // Your custom implementation }
    
        public function create($object){ // Your custom implementation }
    
        public function create($object){ // Your custom implementation }
    
    }
    

    2) Register your new model manager as a service (not needed if you use Symfony 3.3 with the default container configuration, which includes automatic configuration of classes as services)

    # services.yml
    
    ...
    AppBundle\Admin\MyCustomModelManager:
        arguments: [ '@doctrine' ]
    ...
    

    3) Configure your admin class to use your custom model manager, for example:

    app.admin.myadmin:
        class: AppBundle\Admin\MyAdmin
        tags:
            - { name: sonata.admin, manager_type: orm }
        arguments: [~, AppBundle\Entity\MyEntity, ~]
        calls:
            - [ setModelManager, [ '@AppBundle\Admin\MyCustomModelManager' ]]
    

    Hope it helps :)