I have two controllers, one that record the modified entities and put them in a session:
public function update_accountAction(Request $request)
{
Try
{
$code = $request->request->get('code');
$name = $request->request->get('name');
$em = $this->getDoctrine()->getManager();
$repo = $em->getRepository('NRtworksChartOfAccountsBundle:Accounttree');
$to_change = new Accounttree();
$to_change = $repo->findOneByCode($code);
$to_change->setName($name);
$to_change->setCode($code);
$session = $this->getRequest()->getSession();
$entity_to_update = $session->get('entity_to_update');
$counter = $session->get('number_of_changes');
$entity_to_update[] = $to_change;
$counter = $counter +1;
$session->set('number_of_changes',$counter);
$session->set('entity_to_update',serialize($entity_to_update));
$response = array("code" => 100, "success" => true, "modified" => $entity_to_update);
return new Response(json_encode($response));
}
Catch(Exception $e)
{
$response = array("code" => 100, "success" => false, "error" => $e);
return new Response($response);
}
}
And another one that loop on the results, and if it's actually one of the desired object persist it. Finally I flush.
public function save_changesAction()
{
Try
{
$em = $this->getDoctrine()->getManager();
$session = $this->getRequest()->getSession();
$entity_to_update = unserialize($session->get('entity_to_update'));
foreach($entity_to_update as $account)
{
if($account->getId())
{
$em->persist($account);
echo $account->getId();
}
else
{
echo "error";
}
}
$em->flush();
$response = array("code" => 100, "success" => true, "modified" => $account->getId());
return new Response(json_encode($response));
}
Catch(Exception $e)
{
$response = array("code" => 100, "success" => false, "error" => $e);
return new Response($response);
}
}
So the result of this is: ContextErrorException: Notice: Undefined index: 000000007a60b041000000007ae6afd8 in /home/eagle1/www/Symfony24/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php line 2852
I don't understand why, because it seems that I get back a fully functional object (I can execute its functions, access its property and it seems also that the persist is working...
Somebody knows the answer ?
When you pull object from session, it is not managed by doctrine. You have to merge it back to notify entity manager about it.
if($account->getId())
{
$account = $em->merge($account);
$em->persist($account);
echo $account->getId();
}
Doctrine has manual section for Entities in the Session