function hook_ENTITY_TYPE_predelete

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

Act before entity deletion of a particular entity type.

Parameters

\Drupal\Core\Entity\EntityInterface $entity: The entity object for the entity that is about to be deleted.

See also

hook_entity_predelete()

Related topics

File

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

Code

function hook_ENTITY_TYPE_predelete(\Drupal\Core\Entity\EntityInterface $entity) {
    $connection = \Drupal::database();
    // Count references to this entity in a custom table before they are removed
    // upon entity deletion.
    $id = $entity->id();
    $type = $entity->getEntityTypeId();
    $count = \Drupal::database()->select('example_entity_data')
        ->condition('type', $type)
        ->condition('id', $id)
        ->countQuery()
        ->execute()
        ->fetchField();
    // Log the count in a table that records this statistic for deleted entities.
    $connection->merge('example_deleted_entity_statistics')
        ->keys([
        'type' => $type,
        'id' => $id,
    ])
        ->fields([
        'count' => $count,
    ])
        ->execute();
}

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