Doctrine don't update properties of cmf SeoBundle object after setting

52 Views Asked by At

I use symfony cmf seoBundle. My entity class use SeoAwareTrait. When I try to update my seo properties(i use code below) I get result with old values of properties.

    $entity = $this->galleryManager->findByLink($link);


                $entity->getSeoMetadata()->setTitle($metaTitle);
                $entity->getSeoMetadata()->setMetaDescription($metaDescription);
                $entity->getSeoMetadata()->setMetaKeywords($metaKeywords);

                $em->persist($entity);
                $em->flush();

When I try to clone my seo properties Doctrine successfully save my new values:

   $entity = $this->galleryManager->findByLink($link);


                $entity->getSeoMetadata()->setTitle($metaTitle);
                $entity->getSeoMetadata()->setMetaDescription($metaDescription);
                $entity->getSeoMetadata()->setMetaKeywords($metaKeywords);

                $entity->setSeoMetadata(clone $entity->getSeoMetadata());

                $em->persist($entity);
                $em->flush();

Why in the second case the doctrine updates the result, but not in the first? Do I correctly understand that the doctrine does not perceive changes in the properties that refer to other objects?

1

There are 1 best solutions below

0
Thomas Baier On

In the first example you call the methods "setTitle", "setMetaDescription", "setMetaKeywords" on the result of "getSeoMetadata". This result is not $entity, but you excplicity flush only $entity.

See:

$entity->getSeoMetadata()

Returns something (i gues a object) and you set the data on the object not on $entity:

$entity->getSeoMetadata()->setMetaKeywords($metaKeywords);

In the above sample "setMetaKeywords()" is called on the RESULT of "getSeoMetadata()". What you get back from this method?

I would do it this way:

$entity = $this->galleryManager->findByLink($link);
$entitySeoMetadata = $entity->getSeoMetadata();

$entitySeoMetadata->setTitle($metaTitle);
$entitySeoMetadata->setMetaDescription($metaDescription);
$entitySeoMetadata->setMetaKeywords($metaKeywords);

/*
* persist only if the item is new. If you have fetched this from doctrine, 
* do not persist it - just flush without persist.
*
* $em->persist($entity); 
*/

$em->flush();