rashidkhan
rashidkhan

Reputation: 472

How to set default country in Symfony3 form?

I'm using Symfony3 form. I have aCountryType in my Symfony form Builder. It's working correctly. But suppose the user belongs to a Company which is based in Spain. For that User I want to set the default country to be Spain and then show the rest of the countries. How can I do this in Symfony3.

I tried this but its not working.

        $builder->add("country", CountryType::class, array(
            "label" => "Country",
            "required" => false,
            "preferred_choices" => array(
                "ES" => "Spain",
            ),
        ));

Thank you for your time.

Upvotes: 2

Views: 2883

Answers (2)

Boschman
Boschman

Reputation: 861

You can use the data option to set the default country.

preferred_choices will put countries at the top of the list, but it will not set them as the default selected option.

This should be the way to go:

->add(
    'Country',
    CountryType::class,
    [
        'data'        => 'ES',
        'label'       => 'Country',
    ]
)

(tested with Symfony 4 and 5)

Upvotes: 1

inforob
inforob

Reputation: 61

In this type Country::class, for use the preferred selection on array you should use:

->add('country', CountryType::class, [
    'preferred_choices' => ['DE'],
    'label' => 'address.form.country.label',
    'attr' => [
        'class' => 'form-control',
        'placeholder' => 'address.form.country.placeholder'
    ],
    'label_attr' => [
        'class' => 'col-sm-2 col-form-label'
    ],
])

Upvotes: 6

Related Questions