Search code examples
symfonytwigrendering

Rendering a choice field type (symfony2) as buttons


I have a problem which I cannot solve. How shall I approach the following: I have a choice field with 4 different entries, which I am rendering perfectly in a select form (twig). However, I would like to show the 4 entries as 4 separate buttons. How do I change the input type of those 4? Or do I have to do anything totally different?

Thanks for your help -AS

edit (new following question):

Alexandru, thanks for your help. That was very helpful. I added in the fields.html.twig the following:

{% block _appbundle_action_Style_widget -%}
    {% for child in form %}
        <input type="button" {{ block('widget_attributes') }}{% if value is defined %} value="{{ value }}"{% endif %}{% if checked %} checked="checked"{% endif %} />
    {% endfor %}
{%- endblock _appbundle_action_Style_widget %}

However, when I render it it tells me that there is an array to string conversion, which somehow does not work. When I delete the widget attributes, value, and checked parts, the buttons are getting rendered without those then.


Solution

  • You have a few options to choose from:

    1. You can create a new field type, let's call it "button_group", that will extend the "choice" type and write the custom Twig for it, something like this: https://github.com/symfony/symfony/blob/2.7/src/Symfony/Bridge/Twig/Resources/views/Form/bootstrap_3_layout.html.twig#L95

    2. You can use the "choice" field type with the option: expanded => true. And create a custom form template for it only for the form you need it in: http://symfony.com/doc/current/cookbook/form/form_customization.html#what-are-form-themes