symfonysymfony-formsdropdowndropdownchoice

Select option of choice dropdown in a form


I want to select an option in the dropdown from the controller. I am trying with the following piece of code:

$form = $this->createForm(new SearchAdvancedType());
$form->get('option')->setData($session->get('option'));

But it is doing nothing in the dropdown. Nothing is selected when the page loads.

To check if the value was well set I print it using:

$form->get('brand')->Data();

and the result was a number (it changes depending of what I choosed in the dropdown before).

I need to know the way to select the value of the dropdown properly.


Solution

  • To preset a select option I would pass the value into the form.

    class MyFormType extends AbstractType
    {
    
        /**
         * @param FormBuilderInterface $builder
         * @param array $options
         */
        public function buildForm(FormBuilderInterface $builder, array $options)
        {
            $builder
                ->add('type', 'choice', [
                    'required' => true,
                    'choices' => ['yes' => 'Yes', 'no' => 'No'],
                    'data' => $options['select_option']
                ])
            ;
        }
    
        /**
         * @param OptionsResolver $resolver
         */
        public function configureOptions(OptionsResolver $resolver)
        {
            $resolver->setDefaults(array(
                'data_class' => null,
                'select_option' => null
            ));
        }
    
        /**
         * @return string
         */
        public function getName()
        {
            return 'my_form';
        }
    
    }
    

    Then in your controller, pass the value in;

    $form = $this->createForm(new MyFormType(), null, ['select_option' => 'no');