Search code examples
phpsymfonytwigformbuildersymfony5

Symfony formbuilder formatting checkboxes


This seems like it should be simple. I'm trying to avoid having to manually build the form, so I'm hoping there's a way to format the output of checkboxes uses formbuilder.

I have an array of values for an expanded entity to render a series of checkboxes drawn from a db. Currently the only way that it will render the output is in a row, and I'd like to be able to add a simple line break, but there's no clear way of entering HTML into the formbuilder template/

My form looks like this:

    $builder
        ->add('ingredients',EntityType::class, array(
            'required' => false,
            'attr' => array('class' => 'form-control'),
            'class' => Ingredient::class,
            'query_builder' => function(IngredientRepository $ir) {
                return $ir->createQueryBuilder('s')
                    ->orderBy('s.name', 'ASC');
            },
            'multiple' => true,
            'expanded' => true,
        ))

In the twig I have this:

{{ form_start(form) }}
{{ form_row(form.ingredients) }}<br>
{{ form_end(form) }}

This of course simply returns all of the fields in one row. I'd like to be able to loop through the individual ingredients and apply formatting, but I'm unsure as to how to do this.

I tried something like this:

{{ form_start(form) }}
    {% for i in form_row(form.ingredients) %}
    {{ i }}<br>
     {% endfor %}
{{ form_end(form) }}

But of course it did not work. I know I can manually build the form in the twig, but again, I'd like to avoid doing so as it feels clunky.

Hoping for suggestions


Solution

  • Okay, so this actually accomplished what I want. I was attempting to use the form string as an array; I just needed to go directly to the array itself. With this I can generate the rows, and then style them with CSS.

    {{ form_start(form) }}
        {% for i in form.ingredients %}
        {{ form_widget(i) }}{{ form_label(i) }}<br>
         {% endfor %}
    {{ form_end(form) }}