Sonata Admin Custom list field template contains link to admin edit object

Johann picture Johann · Dec 3, 2014 · Viewed 7.1k times · Source

I have an admin class of an object of class Car. This object is in relation with Person or Organisation.

I know how to add a column for Person and Organisation, and i have a link to the edit object

$listMapper
->add('person', null, array('admin_code' => 'appli.admin.person'))
->add('factory', null, array('admin_code' => 'appli.admin.factory'))

This create a link (

However i want just one column. I make this :

$listMapper->add('name',null,array('label'=>'Name','template'=>'AcmeBundle:Admin/Car/list_name.html.twig'))

But in my template i want something like this but i don't understand how make the link to the edit object :

{% extends 'SonataAdminBundle:CRUD:base_list_field.html.twig' %}
{% block field%}
{% if object.getPerson %}
    {% set urlObject = 'linkToAdminEditPerson' %}
{% elseif object.getFactory %}
    {% set urlObject = 'linkToAdminEditFactory' %}
{% endif %}
<a href="{{ urlObject }}">{{ object.name }}</a>
{% endblock %}

Thank You

Answer

devilcius picture devilcius · Dec 3, 2014

Assuming both objects have a name property:

{% extends 'SonataAdminBundle:CRUD:base_list_field.html.twig' %}
{% block field %}
    {% if object.getPerson is defined %}
        {% set objectRoute = 'person_edit' %}
    {% elseif object.getFactory is defined %}
        {% set objectRoute = 'factory_edit' %}
    {% endif %}
    <a href="{{ path(objectRoute, { id: object.id }) }}">{{ object.name }}</a>
{% endblock %}

Note that sonata admin bundle creates the edit route based on the $baseRouteName property of the admin class, appending the action name.