DavidODW
DavidODW

Reputation: 417

Show One To Many relationship in sonata admin

I want to show the one-to-many relationshop entity in the sonata admin's show action. I found answer to my problem at ("Sonata admin bundle, manipulate objects"). I try to implement @M Khalid Junaid's solution but I get an error "An exception has been thrown during the rendering of a template ("Warning: nl2br() expects parameter 1 to be string, object given") in SonataAdminBundle:CRUD:base_show_field.html.twig at line 13."

Did anyone here face this problem before?

GroupParticipant.php

class GroupRepresentive {
    ...
    /**
     * @ORM\OneToMany(targetEntity="GroupParticipant", mappedBy="representive", cascade={"persist", "remove"}, orphanRemoval=true)
     */
    public $participant;

    public function __construct() {
        $this->participant = new ArrayCollection();
    }
    ...}

GroupRepresentativeAdmin.php

protected function configureShowFields(ShowMapper $showMapper)
        {
            $showMapper
                ->add('name')
                ->add('eventTitle')
                ->add('email')
                ->add('person')
                ->add('payment.paymentType')
                ->add('payment.bank')
                ->add('payment.userAccountNumber')
                ->add('payment.referenceNumber')
                ->add('payment.paymentAt')
                ->end()
                ->with('Participant')
                ->add('participant', 'null', array(
                    'template' => 'AppBundle::Admin/groupParticipant.html.twig'
                ))
            ;

        }

groupParticipant.html.twig

{% extends 'SonataAdminBundle:CRUD:base_show_field.html.twig' %}
{% block field %}
    {% spaceless %}

    {% endspaceless %}
{% endblock %}

I put the custom template at

enter image description here

Upvotes: 1

Views: 3398

Answers (2)

Vinoth Kumar
Vinoth Kumar

Reputation: 663

Though the previous answer have been accepted, I'm providing solution for users who are using Symfony 4 and Symfony 3.4 (Symfony Flex).

Field in Admin class must be like:

GroupRepresentativeAdmin.php

->add('participant', 'null', array(
                    'template' => 'folderName/fileName.html.twig'
                ));

Note that the folder must be in your templates directory. The path to your twig file must be templates/folderName/fileName.html.twig

The content in twig file must be like:

fileName.html.twig

{% extends '@SonataAdmin/CRUD/base_show_field.html.twig' %}

{% block field %}
    {% spaceless %}
           //Your custom operation
    {% endspaceless %}
{% endblock %}

Upvotes: 0

Anas EL KORCHI
Anas EL KORCHI

Reputation: 2048

Because you didn't really extend the

SonataAdminBundle:CRUD:base_show_field.html.twig

try this

    {% block field %}
         {# show a field of your entity for example the name #}
         {{value.name}}
    {% endblock %}

Upvotes: 4

Related Questions