Search code examples
phpformssymfonytwigchoicefield

ChoiceType of Forms


I have a Symfony app with this form:

$builder->add('test', ChoiceType::class, [
                 'choices' => ['a' => 1, 'b' => 2],
                 'multiple' => false,
                 'mapped' => false,
                 'expanded' => true,
            ]);

I display it with {{ form_widget(form.test) }} and I get :

<div id="task_test">
    <div class="form-check">
        <input type="radio" id="task_test_0" name="task[test]" required="required" class="form-check-input" value="1">
        <label class="form-check-label required" for="task_test_0">a</label></div>
    <div class="form-check">
        <input type="radio" id="task_test_1" name="task[test]" required="required" class="form-check-input" value="2">
        <label class="form-check-label required" for="task_test_1">b</label>
    </div>
</div>

I want to get this HTML code:

<div id="task_test">
    <div class="form-check d-inline-block custom-control custom-radio mr-1">
        <input type="radio" id="task_test_0" name="task[test]" required="required" class="form-check-input custom-control-input" value="1">
        <label class="form-check-label required custom-control-label" for="task_test_0">a</label></div>
    <div class="form-check d-inline-block custom-control custom-radio">
        <input type="radio" id="task_test_1" name="task[test]" required="required" class="form-check-input custom-control-input" value="2">
        <label class="form-check-label required custom-control-label" for="task_test_1">b</label>
    </div>
</div>

Solution

  • this will not be the same you want, but at least its close to it

    $builder->add('test', ChoiceType::class, [
        'choices' => [
            'a' => 1,
            'b' => 2,
        ],
        'multiple' => false,
        'mapped' => false,
        'expanded' => true,
        'row_attr' => [
            'class' => 'd-inline-block custom-control custom-radio mr-1',
        ],
        'label_attr' => [
            'class' => 'custom-control-label',
        ],
        'choice_attr' => [
            'class' => 'custom-control-input',
        ],
    ]);
    

    if you want exactly that html output, then you have to edit your vendor template