Wednesday, February 9, 2011

Translate form labels inside Twig templates

In this exmaple I assume you've a configured transaltion service up and running. This tip works when you're iterate over loops, like in this example and/or when you print everything out by hand ({{ form_label(form.my_field, label) }}).
{% block someblock %}
    <form action="#" method="post" {{ form_enctype(form) }}>
        {{ form_errors(form) }}

        {% for field in form %}
            {% if not field.ishidden %}
                <div>
                    <!-- translates the field name (stored in key) and saves it in the variable label -->
                    {% set label %}{% trans field.key %}{% endset %}   
                    
                    <!-- passes the translated name as the second parameter for your own label -->
                    {{ form_label(field, label) }}

                    {{ form_errors(field) }}
                    {{ form_field(field) }}
                </div>
            {% endif %}
        {% endfor %}

        {{ form_hidden(form) }}
        <input type="submit" />
    </form>
{% endblock %}

1 comment:

  1. Where did you find the ishidden method which you use on your field to skip the hidden fields? I am asking because when I try this my template doesn't render and I get the following error back:

    Method "ishidden" for object "Symfony\Component\Form\FormView" does not exist

    ReplyDelete