0
votes

In Symfony 2, I'm trying to create a Twig form template to display Bootstrap-like form widgets. Thanks to this article I got a head start. Simple widgets like the one below do work.

…
{% block form_widget_simple %}
{% spaceless %}
    {% set type = type|default('text') %}
    <input class="form-control" type="{{ type }}" {{ block('widget_attributes') }} {% if value is not empty %}value="{{ value }}" {% endif %}/>
{% endspaceless %}
{% endblock form_widget_simple %}
…

This block is called with the code below.

{{ form_row(aanmeld_form.username, {'attr': {'placeholder': 'Gebruikersnaam'}, 'label': 'Gebruikersnaam', 'label_attr': {'class': 'sr-only'}}) }}

Now I would like to build up on these simple widgets to cater for Bootstrap 3's input groups.

I know there are many packages for integrating Bootstrap 3 into Symfony 2, like MopaBootstrapBundle and BraincraftedBoostrapBundle. Willing to keep my code as slim as possible, I would like to be able to get the same result only modifying the Twig form widgets.

The idea was to incorporate an extra variable when calling the widget, like so.

{{ form_row(aanmeld_form.username, {'input_group': { 'prepend': '@' }, 'attr': {'placeholder': 'Gebruikersnaam'}, 'label': 'Gebruikersnaam', 'label_attr': {'class': 'sr-only'}}) }}

However, when I try to do something with this 'input_group' variable, Symfony doesn't know of this variable.

{% block form_widget_simple %}
{{ input_group }}
{% spaceless %}
    {% set type = type|default('text') %}
    <input class="form-control" type="{{ type }}" {{ block('widget_attributes') }} {% if value is not empty %}value="{{ value }}" {% endif %}/>
    {% endspaceless %}
{% endblock form_widget_simple %}

This code results in this error. Variable "input_group" does not exist.

Is it even possible to store extra variables in the call for Twig form widgets? Am I forgetting something?

1

1 Answers

1
votes

You can't just add an option to an element that is not defined for that element. You might consider creating your own custom form field. This sample displays how you can create a drop-down containing child form fields. You would need something similar, but change it so that the children elements are wrapped inside the input group div. For additional information you can check existing form types and extract the code you need from there.