phpformssymfonydynamicdynamic-forms

Symfony Forms Error: Entity of type "..." passed to the choice field must be managed. Maybe you forget to persist it in the entity manager


Objective

I am trying to make a basic form that signs a new player up for a sport. This is taken from the Symfony example at:

https://symfony.com/doc/current/form/dynamic_form_modification.html#form-events-submitted-data

The Code

I have 3 entities:

PlayerList https://github.com/ChimeraBlack1/Symphart/blob/main/src/Entity/PlayerList.php

Sport https://github.com/ChimeraBlack1/Symphart/blob/main/src/Entity/Sport.php

Position https://github.com/ChimeraBlack1/Symphart/blob/main/src/Entity/Position.php

I have a form:

NewPlayerType https://github.com/ChimeraBlack1/Symphart/blob/main/src/Form/NewPlayerType.php

I have a controller:

NewPlayerController https://github.com/ChimeraBlack1/Symphart/blob/main/src/Controller/NewPlayerController.php

The Error:

Entity of type "Doctrine\Common\Collections\ArrayCollection" passed to the choice field must be managed. Maybe you forget to persist it in the entity manager?

Details:

I seem to get this error whenever I create a form using the form builder that is of type, "EntityType" like so:

Reference: https://github.com/ChimeraBlack1/Symphart/blob/main/src/Form/NewPlayerType.php (line 22)

    ->add('sport', EntityType::class, [
        'class' => Sport::class,
        'query_builder' => function(EntityRepository $er) {
            return $er->createQueryBuilder('s')
                ->orderBy('s.sport', 'ASC');
        },
        'choice_label' => 'sport',
    ])

It seems to me that this is happening because I am referencing "Sport::class" in the "NewPlayerType" form. If I were to reference the "PlayerList::class", I don't experience the error. But how do I get fields based on other entities like this to populate on a single form? I'm missing something here conceptually I think...


Solution

  • OK, I figured it out after something like 20 hours of googling, facepalming and rage tears.

    The problem was with the relationship I had setup between entities. I had "OneToMany" relationships where I should have had "ManyToOne".

    If you ever you see this issue, re-write your relationships from a "backwards" perspective, and that should do the trick.

    Thanks!