The following code snippets should be compatible with Drupal 10+.
Challenges in detecting meaningful entity changes
One working with entities in Drupal answering of the following seemingly simple questions can pose a challange:
Has this entity meaningfully changed since its last revision? Has it changed meaningfully since it was last saved?
Drupal doesn't provide a built-in mechanism for this. That's intentional, because what counts as a change can vary greatly between use cases. While there are ways to hack around the problem—such as comparing $entity->toArray()
with $entity->original->toArray()
—these approaches fall short quickly.
- Timestamps, UUIDs, and metadata fields will almost always differ, even when the entity's "meaningful" data hasn't changed.
- Some values are normalized differently on save (for example,
0
stored as an integer versusfalse
cast as a boolean). - Rich text fields often come back from CKEditor with extra markup or formatting quirks, even when the human-readable content is the same.
- The moderation module forces the creation of new revisions even if there have been no changes since the last version of the entity.
This makes raw array comparisons noisy and unreliable.
Enter the Diff Module
Luckily, Drupal already has a well-established module for detecting meaningful changes between entity revisions: Diff.
The Diff module is designed to highlight what actually changed between two revisions of an entity. It provides a user-friendly UI for visualizing differences, but behind that UI is a powerful service that can be reused programmatically.