In symfony2 with sonata: How to pass a variable to the template defined for a given field of the listmapper in the method configureListFields?

listfield, sonata-admin, symfony-sonata

Solution

Try in the Twig

field_description.options.YOURFIELDNAME

defined here

->add('date', 'date', array(
                    'template'   => "AcmeBundle:CRUD:list_date.html.twig",
                    'YOURFIELDNAME' => 'Blablo'
                ))

Cheers

Problem

Using Symfony2 with Sonata, in a list, fields templates can be overwritten and assigning variables to templates, i.e setTemplateVar(), can sometimes be useful! (not talking about form where 'attr' serves this purpose but list...) I would like to know what would be the best approach to pass a variable to the template defined for a given field of the listmapper in the method configureListFields ? ``` <?php namespace Acme\AcmeBundle\Admin; use Sonata\AdminBundle\Admin\Admin; use Sonata\AdminBundle\Datagrid\ListMapper; use Sonata\AdminBundle\Datagrid\DatagridMapper; use Sonata\AdminBundle\Validator\ErrorElement; use Sonata\AdminBundle\Form\FormMapper; class AcmeAdmin extends Admin { protected function configureListFields(ListMapper $listMapper) { $listMapper ->addIdentifier('acme_field') ->add('date', 'date', array( 'template' => "AcmeBundle:CRUD:list_date.html.twig", // 'dateFormat' => "Y-m-d",// ---> how to pass this var to twig ? )) ->add('_action', 'actions', array( 'actions' => array( 'edit' => array(), 'delete' => array(), ), )) ; } ``` A solution to the specific problem of translating and formatting the date is already implemented with the twig template as follows: ``` {% block field%} {% if value is empty %} &nbsp; {% else %} {# retrieving the dateFormat variable from the listmapper #} {% if dateFormat is defined %} {{ value|date(dateFormat)|title }} {% else %} {{ value|date('m / Y') }} {% endif %} {# passing the locale in some way here would be great, it is not available in twig.. #} {# scratch that, it is not necessary with intl.extension... #} {% if locale is defined %} {% set dflt_locale = locale %} {% else %} {% set dflt_locale = 'fr_FR.UTF-8' %} {% endif %} {{ value|localizeddate('medium', 'none', dflt_locale)|title }} {% endif %} {% endblock %} ``` However, my goal is to be able to retrieve a variable there from the listmapper. In the example proposed, the dateFormat would be a good one to pass along... The issue about the locale is fine actually, as I realized it does not need to be passed to localizeddate... it is already available through the intl extension. The following post answer lead me to that conclusion as I could not define locale, but by not adding the parameter it was resolved! Localize dates in twigs using Symfony 2 hence: ``` {{ value|localizeddate('medium', 'none')|title }} ``` Cheers in advance for any response related to the dateFormat parameter! Vinz

Original source