Skip to content

Order of events when entities get saved

When working with entity events in ECA, it is crucial to understand the sequence of operations that Drupal performs when an entity is saved. This knowledge helps in choosing the right event for your models and avoiding common pitfalls like infinite loops or data inconsistencies.

The saving process

When an entity is saved, Drupal executes a specific sequence of steps. While the complete process involves many hooks and internal operations, the key events relevant to ECA occur in the following order:

  1. Initialize content entity: The entity object is initialised and default field values are populated.
  2. Presave content entity: This event is triggered before the entity is written to the storage. This is the last chance to modify the entity's properties before they are persisted.
  3. Physical save: The entity data is written to the database (or other storage).
  4. Insert/Update content entity:

Other entity lifecycle events

Beyond the save process, Drupal also triggers events for other operations on entities:

Best practices

Modifying the entity being saved

If you want to modify the entity that triggered the event (e.g., set a field value based on another field):

  • Use the Presave content entity event.
  • Do NOT add an action to save the entity.

Since the Presave event happens before the physical save, any changes you make to the entity object in your ECA model will be automatically included when Drupal proceeds to step 3 (Physical save).

Do not save in Presave

If you add an action to save the entity within a Presave event, you will likely cause an infinite loop or an error, because that save action will trigger the Presave event again.

In the "Entity: save" action, ensure the "Save entity" option is set to no or simply omit the save action if you only modified fields using "Entity: set field value".

Reacting after save

If you need to perform actions that depend on the entity being fully persisted (e.g., sending a notification, creating a related entity, or triggering an external API call):

  • Use the Insert content entity or Update content entity event.
  • If you modify the entity in these events and want those changes to persist, you MUST explicitly save the entity again.

Recursion prevention

Be careful when saving an entity within an Insert or Update event, as this will trigger the save process again (starting from Presave). Ensure your model has conditions to prevent infinite loops (e.g., checking if the change has already been applied).