Symfony / Sonata Admin: List form on Edit form

2.3k views Asked by At

I have a one (category) to many (product) relationship set up, and I'd like to have a list of products show up at the bottom of the edit category page.

It seems like this would be a common thing to do, but I haven't found any way to do it (or any examples of it). I have managed to get the product to display using sonata_type_collection but that gives me a whole edit form for the Product, when I really just want a list of products associated with the category.

Two questions here, really:

Is this possible?

Is it discouraged (which would explain the lack of examples)? If so, why?

2

There are 2 answers

6
stevenll On BEST ANSWER

The fastest way to do what you are looking for is overriding the edit template. At your admin serivce declaration you can do so:

services:
    sonata.admin.mail:
        class: %sonata.admin.category.class%
        tags:
            - { name: sonata.admin, manager_type: orm, group: "Categories", label: "Category" }
        arguments:
            - ~
            - %skooli.category.class%
            - ~
        calls:
            - [ setTemplate, ["edit", "AcmeAdminBundle:CategoryAdmin:edit.html.twig"] ]

Then, under AcmeBundle/Resources/views/CategoryAdmin/edit.html.twig you can have something like this:

{% extends 'SonataAdminBundle:CRUD:base_edit.html.twig' %}
{# Override any block from the parent view if necessary #}
{% block products %}
    <ul>
    {% for product in object.products%}
        <li>{{ product.name }}</li>
    {% endfor %}
    </ul>
{% endblock products %}
7
webDEVILopers On

In your original question you were talking about the edit template of the category. In your comment you want the list to appear in the show action. The latter is easy. As soon as you add your relation to your showFields action they will be shown:

use Sonata\AdminBundle\Show\ShowMapper;

class CategoryAdmin extends Admin
{
    protected function configureShowFields(ShowMapper $showMapper)
    {
        $showMapper
            ->add('products')
        ;    
    }
}

If you don't like the look you can create a custom template. This will work for show and edit: https://sonata-project.org/bundles/admin/master/doc/reference/action_show.html#setting-up-a-custom-show-template-very-useful