I know we can use hook_entity_update()
hook to do something when an entity is updated. But is there an event to listen for node updates/deletes, or other entities such for that matter?
3 Answers
You can't listen to an event. You can either use a hook or implement a method like postSave() in your custom entity.
Here is the order of hooks and other events that happen during an entity save:
Entity::preSave()
is called on entity objects, andFieldItemListInterface::preSave()
on field objects.hook_ENTITY_TYPE_presave()
hook_entity_presave()
- Entity is saved to storage.
Entity::postSave()
is called on the entity object.hook_ENTITY_TYPE_insert()
(new) orhook_ENTITY_TYPE_update()
(update)hook_entity_insert()
(new) orhook_entity_update()
(update)
-
So entities won't dispatch any events that I can subscribe to? I would have to use a hook?– JohnCommented Dec 3, 2016 at 0:10
-
1Yes, many Drupal specific events are still in hooks. Eventually all hooks will be replaced, see drupal.org/node/1509164 and drupal.org/node/1972304.– 4uk4Commented Dec 3, 2016 at 13:07
Ideally you would listen for entity related events but these aren't ready yet. See "Add events for matching entity hooks".
For now, if you're wanting to stay away from hooks, you can use a contrib module: Hook Event Dispatcher
A node
is an entity type, so hook_ENTITY_TYPE_update(..
is the same as hook_node_update(..
,
function hook_node_update(Drupal\Core\Entity\EntityInterface $entity) {
//$entity->bundle() - 'article' 'page'
}
or
function hook_customentity_update(Drupal\Core\Entity\EntityInterface $entity{
//$entity->bundle() - 'awesome_entity_bundle'
}