Daniel Ribeiro
Daniel Ribeiro

Reputation: 10234

Custom Symfony ChoiceList way of rendering choices (grouped in divs)

I have a choice form field that has a lot of options that I need to group somehow so that they will be rendered divided in groups, maybe placed inside different divs.

I'm currently trying to implement the ChoiceListInterface to achieve that, but I don't know how to implement the methods so I can render the choices divided by groups, but the docs does not clarify how to do that..

The choices always get rendered together.

Upvotes: 0

Views: 341

Answers (1)

goto
goto

Reputation: 8164

You have this array

$grouped_choices = array(
    'Swedish Cars' => array(
        'volvo' => 'Volvo',
        'saab' => 'Saab',
    ),
    'German Cars' => array(
        'mercedes' => 'Mercedes',
        'audi' => 'Audi'
    )
);

First way: quick and simple

$builder->add($name, 'choice', array(
            'choices'   => $grouped_choices),
)

But I don't thinks it works with 'expanded' => true

So there is another way, more customizable (maybe more dirty) In your FormType

foreach($grouped_choices as $name => $choices) {
  $builder->add($name, 'choice', array(
    'choices'   => $choices),
    'expanded'  => true, //custom the widgets like you wants
);

}

Let the controller send the array to the view, then in the view

{% for name, choices in grouped_choices %}
  <div class="whatever">
   {{ form_row(name) }}
  </div>
{% endfor %}

Upvotes: 2

Related Questions