Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SonataAdminBundle - check changes in `preUpdate` hook

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?

like image 666
NHG Avatar asked Feb 04 '14 15:02

NHG


2 Answers

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
    }
}
like image 127
Geert Wille Avatar answered Sep 25 '22 07:09

Geert Wille


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

like image 39
Tersoal Avatar answered Sep 23 '22 07:09

Tersoal