1

I have created a form on a Symfony CRM using the buildForm() function in a form type file. This form includes a choice drop down consisting of simple "yes" and "no" options which map to 1 and 0 respectively. I need to be able to have "no" as the default as my client more often will select this option over the "yes". After reading the documentation here I figured that the preferred_choices option would suit my needs.

Here is my entry in the buildForm() :

$builder->add('non_rider', ChoiceType::class,
    array(
        'label' => 'Is Non-Rider',
        'required' => true,
        'placeholder' => false,
        'choices' => array(
            'Yes' => 1,
            'No' => 0
        ),
        'preferred_choices' => array(0,1),
        'label_attr' => array(
            'class' => 'control-label'
        ),
        'attr' => array(
            'class' => 'form-control required'
        )
    ));

However, this brings out the order as "Yes" then "No" with "Yes" as the default selected option. I was wondering if it reads 0 as null, which means it doesn't register? Is there any way to make "No" the auto-selected option on form load?

Michael Emerson
  • 1,774
  • 4
  • 31
  • 71
  • You can use the "data" option as mentioned here https://symfony.com/doc/current/reference/forms/types/choice.html, and show in action here https://stackoverflow.com/a/35772605/2476843 – Thierry Feb 13 '18 at 09:42
  • Thanks for this - can you write it up as an answer so I can select it as correct? – Michael Emerson Feb 13 '18 at 09:45

1 Answers1

2

You can use the "data" option as mentioned here symfony.com/doc/current/reference/forms/types/choice.html, and show in action here http://stackoverflow.com/a/35772605/2476843

$builder->add('non_rider', ChoiceType::class,
array(
    'label' => 'Is Non-Rider',
    'required' => true,
    'placeholder' => false,
    'choices' => array(
        'Yes' => 1,
        'No' => 0
    ),
    'data' => 0,
    'preferred_choices' => array(0,1),
    'label_attr' => array(
        'class' => 'control-label'
    ),
    'attr' => array(
        'class' => 'form-control required'
    )
));
Thierry
  • 746
  • 13
  • 15
  • 1
    Just to clarify here though, it's the value of the option, not the display name. So, it will only work as `'data' => 0` – Michael Emerson Feb 13 '18 at 09:50
  • 1
    `'data'=>0` overrides any value, i.e, even if the form field saved as 1, it will render every time with 0 – Anant Jul 13 '18 at 04:57