Doctrine EntityListener Pills: Comparing old and new values when updating data

You all, at some point, faced the necessity to compare old and new values when storing an entity.
Here is where Doctrine EntityListener comes at help.

Let imagine you have this User entity

and you want to notify the user when the email address has been changed.

All you have to do is create an EntityListener as described here and end up with something like this:

The core is the preUpdate method. It will be called every time there will be a flush on User entity before making any updates.
The preUpdate method is only one of all methods you can use. You can find more informations here.
Remember that every event has its own peculiarities and limitations, check it in the doc.

Now you only need to check for changes using hasChangedField method passing the name of the property you want to check. Here it’s where all happen.

You don’t have to bother about entity change sets, units of works, etc. The hasChangedField method takes care of this for you and if you need/want to access the previous stored email address and the new one you simply need to call getOldValue and getNewValue methods.

I hope you found it useful and stay tuned for more tips.

Matteo Moretti
Matteo Moretti
Articoli: 30

Lascia una risposta

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *

Questo sito usa Akismet per ridurre lo spam. Scopri come i tuoi dati vengono elaborati.