KTOV KTOV - 21 days ago 10
Twig Question

Displaying returned array as radio buttons

I'm trying to display a set of radio buttons (male or female) on my index page. Within my Form I build the form like this:

public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('gender', ChoiceType::class, array(
'choices' => array(
'Male' => 1,
'Female' => 2,
)));
}


Then within the Controller:

public function indexAction(Request $request)
{
$participantEntry = new Participants();

$form = $this->createForm(ParticipantsType::class, $participantEntry,[
'action' => $request->getUri()
]);

$form->handleRequest($request);

return $this->render('SurveyBundle:Page:index.html.twig',
['form' => $form->createView()]);

}


However, I'm not sure how to actually display as RadioButtons within my Twig file, this is what I've tried:

{% for g in form.gender %}
{{ g.value }}
{% endfor %}


BTW: The $gender within my Entity is an int

Which doesn't work, does anyone know what I am doing wrong?

Answer

Change the add into builder as follow

->add('gender', ChoiceType::class, array(
    'choices'  => array(
        'Male'   => 1,
        'Female' => 2,
    ),
    'expanded' => true,
    'multiple' => false 
);

The combination of 'expanded' => true and 'multiple' => false will generate radio buttons, then in twig, just use

form_widget(form.gender)
Comments