0

I have a form with a dropdown (select) and I would like to choose the option selected by default:

This is the code that generates the select:

    $builder->add('language', 'choice', array(
        'label' => 'pages.age.gateway.language.label',
        'choices' => array(1 => 'first option', 2 => 'second option'),
    ));

I've tried the following (suggested here, Symfony2 Setting a default choice field selection):

    $builder->add('language', 'choice', array(
        'label' => 'pages.age.gateway.language.label',
        'choices' => array(1 => 'first option', 2 => 'second option'),
        'data' => '2'
    ));

this didn't work with my code (my understanding of symfony2, I might not be in the right direction).

Another alternative would be using 'preferred_choices' but I'd like to avoid this, as I wouldn't like to modify the order in which the options are displayed.

Community
  • 1
  • 1
Luis Evrythng
  • 1,085
  • 10
  • 15

2 Answers2

1

If your form depends of an entity:

/* Action */
public function myAction()
{
    $user = new User();
    $user->setLanguage(2); // Set the default option
    $form = $this->createForm(new UserType(), $user); // Give the user to the form

    if ($request->getMethod() == 'POST') {

            $form->bindRequest($request);

            if ($form->isValid()) {

                $user = $form->getData();
                // Do something like save / redirect
            }
     }

     return array(
        'form' => $form->createView(),
     );
}

Also you can set a preferred choice (but not a true default value) thanks to preferred_choices key (it move up the value to the top of the select):

$builder->add('language', 'choice', array(
        'label' => 'pages.age.gateway.language.label',
        'choices' => array(1 => 'first option', 2 => 'second option'),
        'preferred_choices' => 2
));
Sybio
  • 8,565
  • 3
  • 44
  • 53
  • 1
    The option 'preferred_choices' can't be an integer; it has to be traversable in some way. It can be an array, Traversable, callable, string, or PropertyPath. If not, you'll get an InvalidOptionsException. – squaretastic Sep 21 '15 at 19:24
-1

You want to add option without the value. You can do this with option empty_value.

    $builder
        ->add('gender', 'choice', array(
            'label'       => 'Gender',
            'choices' => array('male', 'female'),
            'empty_value' => 'Please select option'
    ));
Djuki
  • 105
  • 2
  • 5