Sonata/symfony - parent/child structure setup

前端 未结 1 595
梦如初夏
梦如初夏 2020-12-31 22:03

I\'ve been asking for this for a while. Can\'t believe there\'s not a single dev that wouldn\'t know the answer and I\'m a little desperate

In Sonata, I cannot make

相关标签:
1条回答
  • 2020-12-31 22:41

    I will use the example provided by Sonata in my explanation, a basic Post/Comment relation.

    You must have a parent/child link (oneTomany / manyToOne relation) between your entities Post (parent) and Comment (child).

    You must add in the service declaration the arguments addChild which target the child Admin service:

    services.yml

    sonata.news.admin.comment:
        class: Sonata\NewsBundle\Admin\CommentAdmin
        arguments: [~, Sonata\NewsBundle\Model\Comment, SonataNewsBundle:CommentAdmin]
        tags:
            - {name: sonata.admin, manager_type: orm, group: "Content"}
    sonata.news.admin.post:
        class: Sonata\NewsBundle\Admin\PostAdmin
        arguments: [~, Sonata\NewsBundle\Model\Post, SonataNewsBundle:PostAdmin]
        tags:
            - {name: sonata.admin, manager_type: orm, group: "Content"}
        calls:
            - [addChild, ['@sonata.news.admin.comment']]
    

    In your CommentAdmin class, you need to add the propertyAssociationMapping to filter this child by parent.

    CommentAdmin

    class CommentAdmin extends Admin
    {
        protected $parentAssociationMapping = 'post';
        ...
    }
    

    Then you will have a new route available: /parent/ID/child/list, you can use the console to figure out the identifier of your new route (php app/console router:debug). If you want an easy way to access this in the admin, i suggest adding a button in the parent Admin list to access directly to its child comments:

    Create a template which add a button to access to the childs comments:

    post_comments.html.twig

    <a class="btn btn-sm btn-default" href="{{ path('OUR_NEW_CHILD_ROUTE_ID', {'id': object.id }) }}">Comments</a>
    

    Then add the button action in the parent Admin in this case PostAdmin:

    PostAdmin

    class PostAdmin extends Admin
    {
        protected function configureListFields(ListMapper $listMapper)
        {
            $listMapper->add('_action', 'actions', array(
                'actions' => array(
                    'show' => array(),
                    'edit' => array(),
                    'comments' => array('template' => 'PATH_TWIG')
                )
            ))
        }
    }
    

    Hope you learned a bit more on how to set parent / child admins.

    0 讨论(0)
提交回复
热议问题