Search code examples
symfonysymfony-forms

How to make RadioButton in Symfony Form?


I have form that i have to redo with Symfony Form but i stuck on this place:

<div class="currency-label">
    <input checked id="cur1" name="currency" type="radio">
    <label for="cur1">EURO</label>
</div>
<div class="currency-label active">
    <input id="cur2" name="currency" type="radio">
    <label for="cur2">USD</label>
</div>

This is how it looks: how it should look

how to make radiobutton with Symfony Forms? In my form class i added:

->add('vacancyCurrency', RadioType::class, ['required' => false])

and to my template

{{ form_widget(form.vacancyCurrency) }}

my form became shorter and obviously no css : how it looks without css and if i add css class to form it looks differently :

{{ form_widget(form.vacancyCurrency, {'attr':
      {'class': 'currency-label'}
}) }}

description 1


Solution

  • So that is how i solved this, in template:

     {{ form_start(form) }}
     {% form_theme form _self %}
     {% block choice_widget %}
         {% for child in form.vacancyCurrency %}
             <div class="currency-label">
                 {{- form_widget(child) -}}
                 {{- form_label(child, null) -}}
             </div>
         {% endfor %}
     {% endblock choice_widget %}
     {{ form_end(form) }}
    

    in form class:

    ->add('vacancyCurrency', ChoiceType::class, [
        'choices' => [
            'USD' => 'USD',
            'RUB' => 'RUB',
        ],
        'expanded' => true,
    ])
    

    and to make one of them active i set default data in model:

    public $vacancyCurrency = 'RUB';
    

    Update

    now i have interface for currency and use it in form class:

    ->add('currency', ChoiceType::class, [
        'label' => 'Валюта',
        'choices' => \array_combine(CurrencyInterface::ALL, CurrencyInterface::ALL)
    ])