Sonata/symfony - parent/child structure setup

半城伤御伤魂 提交于 2019-11-30 10:02:50

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.

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