Thanks to visit codestin.com
Credit goes to github.com

Skip to content

DoctrineBridge: "EntityType" field with "multiple" and "choice_value" options does not correctly handle choices after update above 5.0.x branch #42394

Closed
@noofaq

Description

@noofaq

Symfony version(s) affected: symfony/doctrine-bridge >= 5.1.0

Description
I was updating legacy project to use latest symfony libraries and functional tests have found some issues with one form.
Doing some more in-depth debugging I was able to keep everything working properly by locking DoctrineBridge below 5.1.0.

The issue is that rendered form does not show selected correct values. Values are properly stored in the database when form is submitted (verified in the database). Of course they get cleared when form is resubmitted without selecting those options again.

How to reproduce

Used code to setup the field:

        $builder->add('subscribedUsers', EntityType::class, [
                'class' => User::class,
                'choice_value' => 'id',
                'choice_label' => function(User $user) { return $user->getNameAndSurname(); },
                'required' => false,
                'query_builder' => function (EntityRepository $er) {
                    return $er->createQueryBuilder('u')
                        ->orderBy('u.surname', 'ASC')
                    ;
                },
                'multiple' => true,
            ])
        ;

Example in the rendered view:
obraz

Rrelated rows in the database:
obraz

Possible Solution

I have found two alternative workarounds for the issue:

  1. remove choice_value option completely

Changing choice value to callback like:
'choice_value' => function(User $user) { return $user->getId(); },
does not solve the issue.

Once this option is removed form is rendered correctly:
obraz

  1. replace query_builder with choices

Example:

'choices' => $this->entityManager->getRepository(User::class)
                        ->createQueryBuilder('u')
                        ->orderBy('u.surname', 'ASC')
                        ->getQuery()->getResult(),

What also seems to solve the issue.

Additional context

This change happened in-between 5.x releases so it seems to be a breaking change. I haven't also found anything related to that in the changelog.

Additionally the issue does not seem to appear in other EntityType fields where multiple option is set to false.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions