Search code examples
sonata-admin

How can I add a currency field in list with currency string coming from data?


(It is quite simple to add currency field in the list view

protected function configureShowFields(ShowMapper $showMapper)
    {
        $showMapper
            ->add('price', 'currency', [
                'currency' => 'EUR',
                'locale' => 'fr',
            ])
        ;
    }

But what if my currency string (EUR, USD, ...) comes from the data itself (aka not like in the snippet but from a field from the DB table) ?

can I inject the currency string somehow ?


Solution

  • You can set a custom template for your item and then access to your object into it.

        protected function configureShowFields(ShowMapper $showMapper)
        {
            $showMapper
                ->add('price', 'currency', [
                    'currency' => 'EUR',
                    'locale' => 'fr',
                    'template' =>  '@AdminTemplates/sonata/show_currency.html.twig',
                ])
            ;
        }
    
    {# @AdminTemplates/sonata/show_currency.html.twig #}
    {% extends '@SonataAdmin/CRUD/base_show_field.html.twig' %}
    
    {%- block field -%}
        {% spaceless %}
            {%- if value is null -%}
                 
            {%- else -%}
            {{ value|localizedcurrency(object.currencyField) }}
            {%- endif -%}
        {% endspaceless %}
    {%- endblock field -%}
    

    In this example, I use the localizedcurrency from the Twig Intl Extension

    If you are using the SonataIntlBundle, your template can extends show_currency.html.twig, and maybe you would be able to override the currency field option.

    Hope this helps