Apr12

Tagged in:, , , , Comments:

Sonata Admin Bundle nested list or has child list

Post (parent) to display comments (child) list.

Creating list of rows on sonata admin bundle is fairly easily with there documentation. But when you want to go bit advance on creating sub list of parent entity, then you would be scratching your head.  Luckily this post will help you overcome this very easily.

Assuming you already have PostAdmin and CommentAdmin class to display list individually, if you don’t then please create them first.

We will tell our child class, who is his father (parent). 

// .. YourBundle/Admin/CommentAdmin.php

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

Now we can create services for parent and child, if you already have created the services, then please make sure you add call method on parent service. 

// .. service.yml

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

That’s it!

We can now add links on post list page, but you can add link on any page as you like. 

Create template to add link

// ..YourBundle/Resources/views/CRUD/post_comments.html.twig

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

Replace OUR_NEW_CHILD_ROUTE_ID with comment list route id, which you can find it with following command line.

$ php app/console debug:route

Now we are ready to add link on post list page for each post. 

// ..YourBundle/Admin/PostAdmin.php

class PostAdmin extends Admin
{
    protected function configureListFields(ListMapper $listMapper)
    {
        $listMapper->add('_action', 'actions', array(
            'actions' => array(
                'show' => array(),
                'edit' => array(),
                'comments' => array('template' => 'YourBundle:CRUD:post_comments.html.twig')
            )
        ))
    }
}

That’s it you are done. Now all post are linked properly with its child comments as oneToMany relationship. 

SonataAdminBundle has so much more to offer, which can be hidden if you are new to it, but once you learn it. Then creating admin area would take you few days or less then week depending on the size of your application. 

Post a Comment

You must be logged in to post a comment.

Back to top