Symfony2 forms hide field with twig

12,432

Solution 1

Old question, but for anyone interested, here is another way of solving this. Check the Twig Template Form Function and Variable Reference.

Example

I have an array of forms and wishes to use the Awesome Bootstrap Checkbox. In twig I access each form variable and create elements manually:

{% for form in forms %}
    {{ form_start(form, {'attr': {'class': 'list-group-item' }}) }}
        <input type="hidden" name="{{ form.title.vars.full_name }}" value="{{ form.title.vars.value }}">
        <div class="checkbox checkbox-info checkbox-circle">
            <input type="submit" name="submit" value="Update" class="btn btn-success pull-right">
            <input type="checkbox" class="styled" id="todo{{ loop.index }}">
            <label for="todo{{ loop.index }}">{{ form.title.vars.value }}</label>
        </div>
    {{ form_widget(form._token) }}
    {{ form_end(form, {'render_rest': false }) }}
{% endfor %}

Edit: The Twig Template Form Function and Variable Reference is only available for Symfony 2.7 and later.

Solution 2

For the time being, we ended up outputting the fields into a hidden div, which let us hide the inputs without having to use the twig function {% do form.name.setRendered %} (which causes the nonrendered fields to be set to null).

The new code looks like this:

{{ form_start(form) }}
    <div class="hidden">
        {{ form_widget(form.name) }}
    </div>
    {{ form_widget(form.quantity) }}
    {{ form_widget(form.submit) }}
{{ form_end(form) }}
Share:
12,432
cellulosa
Author by

cellulosa

Updated on June 26, 2022

Comments

  • cellulosa
    cellulosa almost 2 years

    We have setup a form/view to create an entity which works, but we are trying to add a second form/view to the page (to update the created values) with the field for the related entity hidden. If we submit the form with the hidden field, the field is interpreted as being empty when in fact we just want to skip the need to fill it in/use the previous value.

    {{ form_start(form) }}
        {% do form.name.setRendered %}
        {{ form_widget(form.quantity) }}
        {{ form_widget(form.submit) }}
    {{ form_end(form) }}
    

    If we submit the form, our relation is being removed instead of keeping the previous value. We have also tried to disable the field with {{ form_widget(form.name, { 'attr': {'disabled': 'disabled'} }) }} but this although disable the field, still return the same effect.

    In the controller we can see where the value is stripped when the $form->handleRequest($entity) runs but we cannot find a way to ensure the relationship is kept without displaying the field.