php - Track field changes on Doctrine entity -


i want track changes field of doctrine entity. use symfony 2.5.0 , doctrine 2.2.3.

so far have eventsubscriber subscribes preupdate. here want create new entity stores new , old value , holds reference entity updated.

the problem is, can't find way persist new entity. if persist() in preupdate , flush() in postupdate, works if change 1 entity. if multiple entities changed, error changeset empty.

i tried fiddling different events different results. blank pages, tracking entites not persisted etc.

i think should common use case - can't find examples.

don't use preupdate or postupdate, have problems. take @ onflush instead.

you have access complete changeset @ point, can find out fields have changed, what's been added etc. can safely persist new entities. note docs say, have recompute change sets when persist or change entities.

simple example knocked together, not tested similar want.

public function onflush(onflusheventargs $args) {      $entitymanager = $args->getentitymanager();     $unitofwork = $entitymanager->getunitofwork();     $updatedentities = $unitofwork->getscheduledentityupdates();      foreach ($updatedentities $updatedentity) {          if ($updatedentity instanceof yourentity) {              $changeset = $unitofwork->getentitychangeset($updatedentity);              if (!is_array($changeset)) {                  return null;             }              if (array_key_exists('somefieldinyourentity', $changeset)) {                  $changes = $changeset['somefieldinyourentity'];                  $previousvalueforfield = array_key_exists(0, $changes) ? $changes[0] : null;                 $newvalueforfield = array_key_exists(1, $changes) ? $changes[1] : null;                  if ($previousvalueforfield != $newvalueforfield) {                      $yourchangetrackingentity = new yourchangetrackingentity();                     $yourchangetrackingentity->setsomefieldchanged($previousvalueforfield);                     $yourchangetrackingentity->setsomefieldchangedto($newvalueforfield);                      $entitymanager->persist($yourchangetrackingentity);                     $metadata = $entitymanager->getclassmetadata('yournamespace\yourbundle\entity\yourchangetrackingentity');                     $unitofwork->computechangeset($metadata, $yourchangetrackingentity);                 }             }         }     } } 

Comments

Popular posts from this blog

Fail to load namespace Spring Security http://www.springframework.org/security/tags -

sql - MySQL query optimization using coalesce -

unity3d - Unity local avoidance in user created world -