Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a variable to form_theme?

Tags:

twig

symfony

I want to theme my form so that the field's label show the current locale, something like

Name (en) :

So I would like to rewrite block generic_label like that :

{# form_theme.html.twig #}

{% block generic_label %}
{% spaceless %}
    {% if required %}
        {% set attr = attr|merge({'class': attr.class|default('') ~ ' required'}) %}
    {% endif %}
    <label{% for attrname,attrvalue in attr %} {{attrname}}="{{attrvalue}}"{% endfor %}>{{ label|trans }} (app.session.locale)</label>
{% endspaceless %}
{% endblock %}

and import it in my template :

{% form_theme options 'myBundle:Object:form_theme.html.twig' %}

but the app variable is not accessible in the form template. How can I pass a variable to a form theme ?

like image 706
Matthieu Avatar asked Jan 06 '12 20:01

Matthieu


2 Answers

In current version of twig (as for 2016) it is possible. In your template use the following like this:

{{ form_row(form.content, {'testvar' : 'this is test variable'}) }}

Then, in your theme file, just use:

{{testvar}}

of course instead of form.content you will use the field name you need. Cheers, Chris

like image 146
Chris Avatar answered Oct 23 '22 12:10

Chris


You need to create a form extension in order to get it done. Take a look at

http://toni.uebernickel.info/2011/11/25/how-to-extend-form-fields-in-symfony2.html

to learn how to create the extension.

To have access to session locale, make sure to inject the container. After that you'll be able to get any var value you want.

like image 1
P. R. Ribeiro Avatar answered Oct 23 '22 12:10

P. R. Ribeiro