How to update a form with an EntityType using 'data' option

Viewed 76

I have a form to insert and update users, and a country field which is an entityType similar to this (code in the FormType):

$builder
->add('countries', EntityType::class, [
                'label' => 'Country',
                'required' => true,
                'disabled' => false,
                'class' => Country::class,
                'choice_label' => 'name',
                'empty_data' => null,
                'placeholder' => self::EMPTY_VALUE,
                'data' => $country,
                'query_builder' => function (EntityRepository $er) {
                    return $er->createQueryBuilder('c')
                        ->orderBy('c.name', 'ASC');
                },
                'property_path' => 'country',
                'attr' => [
                    'disabled' => $isEdit
                ],
            ])

I use query builder to load values from the db and populate the select. Then I use

'data' => $country, // $country = $user->getCountry()

to select the current value for $country.

The problem is that when I update the form without changing anything, I lose the value for country. Other values in TextType fields are ok.

the Symfony docs says: https://symfony.com/doc/3.2/reference/forms/types/entity.html#data

"The data option always overrides the value taken from the domain data (object) when rendering. This means the object value is also overriden when the form edits an already persisted object, causing it to lose its persisted value when the form is submitted."

So I suppose this is the reason. Is there a way to submit the form and not to lose the prefilled value?

1 Answers

You have to remove the 'data' => $country option.

As you mentioned:

"The data option always overrides the value taken from the domain data (object) when rendering. This means the object value is also overriden when the form edits an already persisted object, causing it to lose its persisted value when the form is submitted."

It means that any value passed in your form will be replace by the data option value. When updating you entity, the current value will be the default displayed value.

Related