ylliX - Online Advertising Network Quick tip: How to deal with "Entity passed to the choice field must be managed." with Doctrine? - Yet Another Programmer's Blog

Quick tip: How to deal with “Entity passed to the choice field must be managed.” with Doctrine?

Sometimes it is good to store form data in session – for example when working with filters, when you want to save last filters state when user gets back to page. But if your form has Entity type in choice field, you will see error like:
“Entity of type XXX passed to the choice field must be managed. Maybe you forget to persist it in the entity manager?”
How to deal with this? Read below.

Fortunately, solution is very simple – you have to merge your session’s entities, with Doctrine Manager. Here we go with snippet:

$filters = $session->get("filters", []);
foreach ($filters as $key => $filter) {
    if (is_object($filter)) {
        $filters[$key] = $this->getDoctrine()->getManager()->merge($filter);
    }
}
$form = $this->createForm(FormType::class, $filters, ['method' => 'GET']);

So trick is in calling merge() method of Doctrine Manager. But beware – in current version of Persistence (1.3.3) this method is marked as deprecated, and will be removed in 2.0. But until then, it will just work.

4 thoughts on “Quick tip: How to deal with “Entity passed to the choice field must be managed.” with Doctrine?

Leave a Reply