ThEBiShOp
ThEBiShOp

Reputation: 516

Symfony3 - How to separate radio buttons from a choicetype

I would like to create a text field with a radio button (input group) and a single radio button above that field. I want the 2 radio buttons to be linked.

Here is an example : https://jsfiddle.net/y8tecoyf/

<div class="form-group">
  <label class="col-sm-4 control-label">Field 1 :</label>
  <div class="col-sm-8 ">
    <div class="input-group">
      <span class="input-group-addon">
        <input type="radio" aria-label="..." name="choice" value="f1">
      </span>
      <input type="text" class="form-control" aria-label="...">
    </div><!-- /input-group -->
  </div>
</div>
<div class="form-group">
  <label class="col-sm-4 control-label">Field 2 :</label>
  <div class="col-sm-8 ">
    <input type="radio" aria-label="..." name="choice" value="f2">
  </div>
</div>

I don't know how to do that since the radio buttons in a choicetype can't be manipulated link distinct fields. Or can I ?

Upvotes: 1

Views: 2693

Answers (1)

PapyDanone
PapyDanone

Reputation: 291

Build your Symfony form class with two fields (the text field + your choice field).

$builder->add('choiceField', ChoiceType::class, array(
    'choices'  => [your choices]
    'expanded' => true,
    'multiple' => false
));
$builder->add('textField')

In your template, you need to split the rendering of the choiceField field. You can either:

  1. use straight HTML as you have in your example, making sure you use the name attribute expected by the Symfony form system to ensure validation works
  2. use the Symfony form rendering where appropriate, as follows:

    {{ form_widget(form.choiceField[0]) }}
    {{ form_widget(form.textField) }}
    {{ form_widget(form.choiceField[1]) }}
    

Method 2 is the preferred one as it will take care of form repopulation.

Upvotes: 1

Related Questions