Symfony/Doctrine entity leads to dirty entity association when merged multiple times with entity manager Symfony/Doctrine entity leads to dirty entity association when merged multiple times with entity manager symfony symfony

Symfony/Doctrine entity leads to dirty entity association when merged multiple times with entity manager


Got it.

For anyone who might run into this problem in the future:

You cannot merge an entity which has unpersisted sub-entities. They become marked as dirty.

I.E

You may have an article with two images already saved to DB.

ARTICLE (ID 1) -> IMAGE (ID 1)               -> IMAGE (ID 2)

If you save serialise the article to session and then unserialize and merge it. It's ok.

If you add a new image, then serialize it to session you will have problems. This is because you cannot merge an unpersisted entity.

ARTICLE (ID 1) -> IMAGE (ID 1)               -> IMAGE (ID 2)               -> IMAGE (NOT YET PERSISTED)

What I had to do was:

After I unserialize the article, I remove the unpersisted images and store them in a temporary array (I check for ID). THEN i merge the article and re-add the unpersisted image(s).

        $article = unserialize($this->session->get('currentArticle'));        $tempImageList = array();        foreach($article->getImages() as $image)        {            if(!$image->getId()) //If image is new, move it to a temporary array            {                $tempImageList[] = $image;                $article->removeImage($image);            }        }        $plug = $this->em->merge($article); //It is now safe to merge the entity        foreach($tempImageList as $image)        {            $article->addImage($image); //Add the image back into the newly merged plug        }        return $article;                        

I can then add more images if need be, and repeat the process until I finally persist the article back to DB.

This is handy to know in the event you need to do a multiple pages creation process or adding images via AJAX.