function hook_entity_insert

Same name and namespace in other branches
  1. 7.x modules/system/system.api.php \hook_entity_insert()
  2. 9 core/lib/Drupal/Core/Entity/entity.api.php \hook_entity_insert()
  3. 10 core/lib/Drupal/Core/Entity/entity.api.php \hook_entity_insert()
  4. 8.9.x core/lib/Drupal/Core/Entity/entity.api.php \hook_entity_insert()

Respond to creation of a new entity.

This hook runs once the entity has been stored. Note that hook implementations may not alter the stored entity data.

Parameters

\Drupal\Core\Entity\EntityInterface $entity: The entity object.

See also

hook_ENTITY_TYPE_insert()

Related topics

File

core/lib/Drupal/Core/Entity/entity.api.php, line 1206

Code

function hook_entity_insert(\Drupal\Core\Entity\EntityInterface $entity) : void {
  // Insert the new entity into a fictional table of all entities.
  \Drupal::database()->insert('example_entity')
    ->fields([
    'type' => $entity->getEntityTypeId(),
    'id' => $entity->id(),
    'created' => \Drupal::time()->getRequestTime(),
    'updated' => \Drupal::time()->getRequestTime(),
  ])
    ->execute();
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.