Reputation: 361
I want to render inputs of type radio inside their labels because I want to use flexbox to justify them with space between each.
Here's part from a RegistrationType class
...
->add('gender', ChoiceType::class, [
'required' => true,
'expanded' => true,
'multiple' => false,
'label' => false,
'choices' => [
'male' => 'male',
'female' => 'female',
'other' => 'other',
],
])
Configure options of this class are default:
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => User::class,
]);
}
I want to acheive given result:
<div style="display:flex; flex-direction:row; justify-content:space-between; width:22rem;">
<label>
<input type="radio"
name="registration_form[gender]"
required="required"
class="required"
value="male">
Male
</label>
<label>
<input type="radio"
name="registration_form[gender]"
required="required"
class="required"
value="female">
Female
</label>
<label>
<input type="radio"
name="registration_form[gender]"
required="required"
class="required"
value="other">
Other
</label>
</div>
Is there any way to do this?
Upvotes: 0
Views: 689
Reputation: 5031
Similar to the accepted answer here, and supported by the Field Variables of the ChoiceType class, you might access the .choices
attribute and loop through it like so:
<div style="display:flex; flex-direction:row; justify-content:space-between; width:22rem;">
{{ form_label(form.gender) }}
<div>
{% for key,val in form.gender.vars.choices %}
<label>
<input type="radio"
name="{{ form.gender.vars.full_name }}"
required="required"
class="required"
value="{{ val.value }}"
/>
{{ val.label | trans }} />
{% endfor %}
</div>
</div>
There are more elegant ways of customizing, like creating or overriding a Form Theme, or, perhaps using a twig macro to keep your code somewhat DRY. If you go the form theme route, look into the way that the attributes block is used – we bypass much of the utility it gives in this example above.
Upvotes: 2