Alex
Alex

Reputation: 1260

Symfony buildForm: place checkbox input inside label tags

I have a form made with buildForm in symfony 5.3

One of the form fields is a checkbox, the 'active' one. This is the code:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        // some other fields
        ->add('active')
    ;
}

formBuilder is printing the checkbox like this:

<div>
    <label for="extract_ac_configuration_active">Active</label>
    <input type="checkbox" id="extract_ac_configuration_active" name="extract_ac_configuration[active]" value="1">
</div>

But because I want the label to be clickable without need of javascript, and because the css framework I'm using, I need it to be rendered as

<label>
    <input type="checkbox" id="extract_ac_configuration_active" name="extract_ac_configuration">
    <span>active</span>
</label>

How can I change the way that checkbox is rendered through buildForm to the one I need?

Upvotes: 0

Views: 802

Answers (1)

ebenjs
ebenjs

Reputation: 429

If you want to exactly have this result :

<label>
    <input type="checkbox" id="extract_ac_configuration_active" name="extract_ac_configuration">
    <span>active</span>
</label>

You must explode the form rendering. Instead of rendering globally like this :

{{ form_widget(form) }}

you must do it like this :

{{ form_start(form) }}

<label>
    {{ form_widget(form.active) }}
    <span>active</span>
</label>

{{ form_end(form) }}

Upvotes: 1

Related Questions