Search code examples
symfonysonata-adminsymfony-3.4

Concat field on custom column in Sonata Admin view


I'm trying to add a custom field to the list view in Sonata Admin where it will concat a fixed string (http://www.example.com) and the field slug as seen below, so that I can access that specific product url. The column shows in the table and the link is created, but I can't figure out how to pass the slug variable to the template so that it works.

I have the following configuration:

 #ProductAdmin.php
    protected function configureListFields(ListMapper $listMapper)
        {

        $listMapper->addIdentifier('id')
            ->addIdentifier('name')
            ->add('date')
            ->add('slug', 'text', [
                'editable' => true
            ])
            ->add('link', 'string', [
                'template' => 'default/admin-link.html.twig',
            ])


#default/admin-link.html.twig
{% extends 'SonataAdminBundle:CRUD:base_list_field.html.twig' %}

{% block field %}
    <a href="https://www.wattdoesituse.com/{{ slug }}">Product link</a>
{% endblock %}

Solution

  • In template you can access object which holds data of current iteration from loop just call {{object.slug}} in template to access slug for particular row like

    {% extends 'SonataAdminBundle:CRUD:base_list_field.html.twig' %}
    
    {% block field %}
        <a href="https://www.wattdoesituse.com/{{ object.slug }}">Product link</a>
    {% endblock %}
    

    Or it would be better if you generate your URLs using route/path method