mpiot
mpiot

Reputation: 1522

Non-mapped form, EntityType and data attribute

I use an EntityType to create a form, but not mapped on an entity. The form is long and the user re-use the same options many times, then when he valid the form, if it's valid, I store the $form->getData() in session.

When I generate the form I inject the $data. It works well for all options, except the EntityType, I don't understand why...

In the $data, I've an ArrayCollection with the objects selected in the EntityType, but the form doesn't select it. I've used mapped = false, because if I remove it I've an error:

Entities passed to the choice field must be managed. Maybe persist them in the entity manager?

Someone I've an idea how to do ?

Upvotes: 2

Views: 2161

Answers (1)

yceruto
yceruto

Reputation: 9575

Settings mapped = false shouldn't be the solution in this case, because you need to write the stored data into this field, right? so mapped = false avoid it (see more about mapped option here)

The problem here is that the EntityType need to get the id value from each item and it requires that these items are managed actually by EntityManager:

Entities passed to the choice field must be managed. Maybe persist them in the entity manager?

An entity is in MANAGED state when its persistence is managed by an EntityManager. In other words, an entity is managed if its fetched from the database or registered as new through EntityManager#persist.

In you case, these entities comes from session, so you have two option:

  • Re-query the stored entities from database:

    if (isset($data['foo']) && $data['foo'] instanceof Collection) {
        $data['foo'] = $this->getDoctrine()->getRepository(Foo::class)->findBy([
            'id' => $data['foo']->toArray(),
        ]);
    }
    
  • Or, set a custom choice_value option to avoid the default one:

    $form->add('foo', EntityType::class, [
        'class' => Foo::class,
        'choice_value' => 'id', // <--- default IdReader::getIdValue()
    ]);
    

Upvotes: 3

Related Questions