Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sonata/symfony - parent/child structure setup

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 the url structure/pattern /parent/ID/child/list work. Went thru the very, rather poor, 4.6. CREATE CHILD ADMINS section in sonata docs, found only a few examples online and I can't make it work

Can someone explain step by step how to set such structure up?

like image 917
belinea Avatar asked Nov 04 '14 21:11

belinea


1 Answers

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.

like image 182
HypeR Avatar answered Oct 15 '22 05:10

HypeR