My code is fairly complex so I will try to explain in the simplest way possible
I have a parent entity ValueList
. This 'list' has many ValueListItems
.
class ValueList
{
//...
/**
* @ODM\ReferenceMany(
* targetDocument="JobboardBase\Entity\ValueListItem",
* sort={"order"="asc"},
* cascade={"all"}
* )
*/
protected $items;
}
I then have a service method that adds a new ValueListItem
to this (already managed) ValueList
.
public function createValueListItem(ValueListItem $item, ValueList $list)
{
try {
$om = $this->getObjectManager();
$om->persist($item);
$list->addItem($item);
$om->persist($list);
$om->flush();
return $item;
} catch (\Exception $e) {
throw $e;
}
}
This adds the entity correctly to the Mongo collection. However because I am executing the controller action with an AJAX call I also need to re-dispatch the 'indexAction' to return a the updated 'list' HTML asynchronously.
// ListItemController::createAndAttachValueItemToParentListAction()
// ....
// Below is the successful 'add' of the above method call return
if ($service->createValueListItem($form->getData(), $list)) {
$content = $this->forward()->dispatch('JobboardBase\Controller\ListItem', array(
'action' => 'index',
'id' => $list->getId()
));
return $this->jsonModel(array(
'success' => true,
'messages' => array($message),
'content' => $content
));
//... IndexAction
public function indexAction() {
// ...
$items = $list->getItems(); // Returns 0 (when there should be 1)
//...
}
The HTML returned via the forward()
call (in $content
) doesn't include the new added ValueListItem
entity. It will however display correctly when I refresh the page.
Doctrine seems to be returning a cached ValueList
entity that doesn't include the newly added ValueListItem
- Only when a new requested is made does the new item get displayed.
My question is why is doctrine returning the 'old' entity rather than the updated entity? I was under the impression that it should be the same instance and therefore updated by reference?