Is it possible to check if field was changed on preUpdate
hook? I'm looking for something like preUpdate
hasChangedField($fieldName)
Doctrine functionality. Any ideas?
Asked
Active
Viewed 5,810 times
7

Vasilii Suricov
- 871
- 12
- 18

NHG
- 5,807
- 6
- 34
- 45
2 Answers
14
This question is a bit similar to this one
Your solution is just to compare the field of the old object with the new one and see where it differs.
So for example:
public function preUpdate($newObject)
{
$em = $this->getModelManager()->getEntityManager($this->getClass());
$originalObject = $em->getUnitOfWork()->getOriginalEntityData($newObject);
if ($newObject->getSomeField() !== $originalObject['fieldName']) {
// Field has been changed
}
}

Community
- 1
- 1

Geert Wille
- 1,656
- 13
- 18
-
1Thx! It was helpful. But this case should work for mongoDB (`getOriginalDocumentData`), for mysql I've used `getOriginalEntityData`. Additionally that function returns array, so I had to refer by `$originalObject['fieldName']`. It would be great if you could update your answer. – NHG Feb 05 '14 at 22:20
-
You were right I corrected my answer. Glad I could help! – Geert Wille Feb 05 '14 at 22:29
-
1Great answer but is there a way we can do this with postUpdate() ? – vimuth May 26 '16 at 06:15
1
For me the best approach is this in Sonata Admin:
$newField = $this->getForm()->get('field')->getData();
$oldField = $this->getForm()->get('field')->getConfig()->getData();
You shouldn't use unit of work unless there is no option. Also, if you have a not mapped field, you can't access it by entity object.
In a normal Doctrine lyfe cycle event, the best option is Doctrine preupdate event doc

Tersoal
- 11
- 2