Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hide form fields in twig template?

I have a Symfony form that includes two TextType fields. If a certain check evaluates to false, I don't want to display the input fields but output the static content of the field and include the form fields as hidden fields instead. How can I do that?

like image 846
Gottlieb Notschnabel Avatar asked Mar 09 '16 18:03

Gottlieb Notschnabel


2 Answers

You can prevent any output for the form field by pretending, that it was already rendered:

{{ form_start(form) }}
    {% if someValue == true %}
        {% do form.fieldName.setRendered() %}
    {% endif %}
{{ form_end(form) }}
like image 91
MaPePeR Avatar answered Oct 13 '22 21:10

MaPePeR


you can use HiddenType, or hide field in template:

{{ form_start(form) }}
    {% if someValue == true %}
        {{ form_widget(form.fieldName) }}
    {% else %}
        {{ form_widget(form.fieldName, { 'attr': {'class': 'hidden-row'} }) }}
    {% endif %}
    {# other fields... #}
{{ form_end(form) }}

or you can use FormEvents like FormEvents::PRE_SET_DATA in FormType. (doc)

like image 13
b3da Avatar answered Oct 13 '22 20:10

b3da