KTOV KTOV - 1 year ago 93
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)
->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()


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 Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download