SonataAdminBundle: Unable to set custom data in show action field

Hey,

I have a show page and I want to add a custom value. I have tried doing what I did in other actions which is to add an array to the third parameter with the data key like so:

    protected function configureShowFields(ShowMapper $showMapper)
    {
        $showMapper
            ->add('name')                      
            ->add('dateEnd')
            ->add('example', null,
                array('data' => 'example value')
            )
        ;
    }

In the configureListFields action this works. I have injected custom values with the data attribute.

How is this suppose to work or is the data key ignored?

About this issue

  • Original URL
  • State: closed
  • Created 9 years ago
  • Reactions: 2
  • Comments: 17 (5 by maintainers)

Most upvoted comments

Anyone who still looks for a solution, I answered here https://stackoverflow.com/a/69740519/2051414 And just duplicate the answer here:

I used this solution. In the configureShowFields() method of an Admin class:

$showMapper
        ->with('Tab Name')
        ->add(
            'any_name',
            null,
            [
                'template' => 'Admin/Custom/any_name_show_template.html.twig',
                'customData' => $this->someRepository->getSomeEntityBy($field),
                'anotherCustomData' => $this->someService->getSomeDataBy($value),
            ]
        )
    ;

In the custom template, you can access custom data by field_description.options.<customFieldName>, so for provided example data accessors would be {{ field_description.options.customData }} and {{ field_description.options.anotherCustomData }}

For the shorter field name in the Twig template, you can do like this:

{% set customData = field_description.options.customData %}

and access the custom data like {{ customData }}

Hope this helps and saves time.

What I did is a workaround, and in any case it’s ugly and should not be done like this, but unless Sonata actually gives a way to make custom queries in the show fields, we have no other choice.

I’ve set a public property in the Admin and in the php configureShowFields() I set that property like this:

$repository = $this
    ->getConfigurationPool()
    ->getContainer()
    ->get('doctrine')
     ->getRepository('MyRepo:MyEntity');
$this->affiliate = $repository->getPartnerByOrderId($orderId);

Added a field to the php $showMapper object like this:

$showMapper->add('affiliate', 'entity', [
    'label' => 'venue.bookings.list.affiliate.label',
    'template' => 'MyBundle:Admin:affiliate.html.twig'
])

Then in the template I accessed it like this:

{% block field %}
    {% if admin.affiliate is not empty %}
        {{ admin.affiliate.label }}
    {% endif %}
{% endblock field %}

I hope this helps anyone.