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.
where in the sea of files would I put this snippet? Almost a useful article…Almost…
This should go before:
$form->handleRequest($request);
in controller.
Check this for an alternative to merge()-funtion.
https://stackoverflow.com/a/66941019/9779846
Have a look at this which avoids the use of MERGE-function
https://stackoverflow.com/a/66941019/9779846