Skip to content

Entity

hook_entity_access

/**
 * Control entity operation access.
 *
 * Note that this hook is not called for listings (e.g., from entity queries
 * and Views). For nodes, see Node access rights documentation for
 * a full explanation. For other entity types, see hook_query_TAG_alter().
 *
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The entity to check access to.
 * @param string $operation
 *   The operation that is to be performed on $entity. Usually one of:
 *   - "view".
 *   - "update".
 *   - "delete".
 * @param \Drupal\Core\Session\AccountInterface $account
 *   The account trying to access the entity.
 *
 * @return \Drupal\Core\Access\AccessResultInterface
 *   The access result. The final result is calculated by using
 *   \Drupal\Core\Access\AccessResultInterface::orIf() on the result of every
 *   hook_entity_access() and hook_ENTITY_TYPE_access() implementation, and the
 *   result of the entity-specific checkAccess() method in the entity access
 *   control handler. Be careful when writing generalized access checks shared
 *   between routing and entity checks: routing uses the andIf() operator. So
 *   returning an isNeutral() does not determine entity access at all but it
 *   always ends up denying access while routing.
 *
 * @see \Drupal\Core\Entity\EntityAccessControlHandler
 * @see hook_entity_create_access()
 * @see hook_ENTITY_TYPE_access()
 * @see hook_query_TAG_alter()
 */
function hook_entity_access(\Drupal\Core\Entity\EntityInterface $entity, $operation, \Drupal\Core\Session\AccountInterface $account): \Drupal\Core\Access\AccessResultInterface {
  // No opinion.
  return AccessResult::neutral();
}

hook_ENTITY_TYPE_access

/**
 * Control entity operation access for a specific entity type.
 *
 * Note that this hook is not called for listings (e.g., from entity queries
 * and Views). For nodes, see Node access rights documentation for
 * a full explanation. For other entity types, see hook_query_TAG_alter().
 *
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The entity to check access to.
 * @param string $operation
 *   The operation that is to be performed on $entity. Usually one of:
 *   - "view"
 *   - "update"
 *   - "delete".
 * @param \Drupal\Core\Session\AccountInterface $account
 *   The account trying to access the entity.
 *
 * @return \Drupal\Core\Access\AccessResultInterface
 *   The access result. hook_entity_access() has detailed documentation.
 *
 * @see \Drupal\Core\Entity\EntityAccessControlHandler
 * @see hook_ENTITY_TYPE_create_access()
 * @see hook_entity_access()
 * @see hook_query_TAG_alter()
 */
function hook_ENTITY_TYPE_access(\Drupal\Core\Entity\EntityInterface $entity, $operation, \Drupal\Core\Session\AccountInterface $account): \Drupal\Core\Access\AccessResultInterface {
  // No opinion.
  return AccessResult::neutral();
}

hook_entity_create_access

/**
 * Control entity create access.
 *
 * @param \Drupal\Core\Session\AccountInterface $account
 *   The account trying to access the entity.
 * @param array $context
 *   An associative array of additional context values. By default it contains
 *   language and the entity type ID:
 *   - entity_type_id - the entity type ID.
 *   - langcode - the current language code.
 * @param string $entity_bundle
 *   The entity bundle name.
 *
 * @return \Drupal\Core\Access\AccessResultInterface
 *   The access result.
 *
 * @see \Drupal\Core\Entity\EntityAccessControlHandler
 * @see hook_entity_access()
 * @see hook_ENTITY_TYPE_create_access()
 */
function hook_entity_create_access(\Drupal\Core\Session\AccountInterface $account, array $context, $entity_bundle): \Drupal\Core\Access\AccessResultInterface {
  // No opinion.
  return AccessResult::neutral();
}

hook_ENTITY_TYPE_create_access

/**
 * Control entity create access for a specific entity type.
 *
 * @param \Drupal\Core\Session\AccountInterface $account
 *   The account trying to access the entity.
 * @param array $context
 *   An associative array of additional context values. By default it contains
 *   language:
 *   - langcode - the current language code.
 * @param string $entity_bundle
 *   The entity bundle name.
 *
 * @return \Drupal\Core\Access\AccessResultInterface
 *   The access result.
 *
 * @see \Drupal\Core\Entity\EntityAccessControlHandler
 * @see hook_ENTITY_TYPE_access()
 * @see hook_entity_create_access()
 */
function hook_ENTITY_TYPE_create_access(\Drupal\Core\Session\AccountInterface $account, array $context, $entity_bundle): \Drupal\Core\Access\AccessResultInterface {
  // No opinion.
  return AccessResult::neutral();
}

hook_entity_type_build

/**
 * Add to entity type definitions.
 *
 * Modules may implement this hook to add information to defined entity types,
 * as defined in \Drupal\Core\Entity\EntityTypeInterface.
 *
 * To alter existing information or to add information dynamically, use
 * hook_entity_type_alter().
 *
 * @param \Drupal\Core\Entity\EntityTypeInterface[] $entity_types
 *   An associative array of all entity type definitions, keyed by the entity
 *   type name. Passed by reference.
 *
 * @see \Drupal\Core\Entity\Entity
 * @see \Drupal\Core\Entity\EntityTypeInterface
 * @see hook_entity_type_alter()
 */
function hook_entity_type_build(array &$entity_types): void {
  /** @var \Drupal\Core\Entity\EntityTypeInterface[] $entity_types */
  // Add a form for a custom node form without overriding the default
  // node form. To override the default node form, use hook_entity_type_alter().
  $entity_types['node']->setFormClass('my_module_foo', 'Drupal\my_module\NodeFooForm');
}

hook_entity_type_alter

/**
 * Alter the entity type definitions.
 *
 * Modules may implement this hook to alter the information that defines an
 * entity type. All properties that are available in
 * \Drupal\Core\Entity\Annotation\EntityType and all the ones additionally
 * provided by modules can be altered here.
 *
 * Do not use this hook to add information to entity types, unless one of the
 * following is true:
 * - You are filling in default values.
 * - You need to dynamically add information only in certain circumstances.
 * - Your hook needs to run after hook_entity_type_build() implementations.
 * Use hook_entity_type_build() instead in all other cases.
 *
 * @param \Drupal\Core\Entity\EntityTypeInterface[] $entity_types
 *   An associative array of all entity type definitions, keyed by the entity
 *   type name. Passed by reference.
 *
 * @see \Drupal\Core\Entity\Entity
 * @see \Drupal\Core\Entity\EntityTypeInterface
 */
function hook_entity_type_alter(array &$entity_types): void {
  /** @var \Drupal\Core\Entity\EntityTypeInterface[] $entity_types */
  // Set the controller class for nodes to an alternate implementation of the
  // Drupal\Core\Entity\EntityStorageInterface interface.
  $entity_types['node']->setStorageClass('Drupal\my_module\MyCustomNodeStorage');
}

hook_entity_view_mode_info_alter

/**
 * Alter the view modes for entity types.
 *
 * @param array $view_modes
 *   An array of view modes, keyed first by entity type, then by view mode name.
 *
 * @see \Drupal\Core\Entity\EntityDisplayRepositoryInterface::getAllViewModes()
 * @see \Drupal\Core\Entity\EntityDisplayRepositoryInterface::getViewModes()
 */
function hook_entity_view_mode_info_alter(&$view_modes) {
  $view_modes['user']['full']['status'] = TRUE;
}

hook_entity_bundle_info

/**
 * Describe the bundles for entity types.
 *
 * Bundles can also be defined with the \Drupal\Core\Entity\Attribute\Bundle
 * attribute applied to a bundle class.
 *
 * @return array
 *   An associative array of all entity bundles, keyed by the entity
 *   type name, and then the bundle name, with the following keys:
 *   - label: The human-readable name of the bundle.
 *   - translatable: (optional) A boolean value specifying whether this bundle
 *     has translation support enabled. Defaults to FALSE.
 *   - class: (optional) The fully qualified class name for this bundle. If
 *     omitted, the class from the entity type definition will be used. Multiple
 *     bundles must not use the same subclass. If a class is reused by multiple
 *     bundles, an \Drupal\Core\Entity\Exception\AmbiguousBundleClassException
 *     will be thrown.
 *
 * @see \Drupal\Core\Entity\EntityTypeBundleInfo::getBundleInfo()
 * @see hook_entity_bundle_info_alter()
 * @see \Drupal\Core\Entity\Attribute\Bundle
 */
function hook_entity_bundle_info(): array {
  $bundles['user']['user']['label'] = t('User');
  return $bundles;
}

hook_entity_bundle_info_alter

/**
 * Alter the bundles for entity types.
 *
 * @param array $bundles
 *   An array of bundles, keyed first by entity type, then by bundle name.
 *
 * @see Drupal\Core\Entity\EntityTypeBundleInfo::getBundleInfo()
 * @see hook_entity_bundle_info()
 */
function hook_entity_bundle_info_alter(&$bundles) {
  $bundles['user']['user']['label'] = t('Full account');
  // Override the bundle class for the "article" node type in a custom module.
  $bundles['node']['article']['class'] = 'Drupal\my_module\Entity\Article';
}

hook_entity_bundle_create

/**
 * Act on entity_bundle_create().
 *
 * This hook is invoked after the operation has been performed.
 *
 * @param string $entity_type_id
 *   The type of $entity; e.g. 'node' or 'user'.
 * @param string $bundle
 *   The name of the bundle.
 *
 */
function hook_entity_bundle_create($entity_type_id, $bundle): void {
  // When a new bundle is created, the menu needs to be rebuilt to add the
  // Field UI menu item tabs.
  \Drupal::service('router.builder')->setRebuildNeeded();
}

hook_entity_bundle_delete

/**
 * Act on entity_bundle_delete().
 *
 * This hook is invoked after the operation has been performed.
 *
 * @param string $entity_type_id
 *   The type of entity; for example, 'node' or 'user'.
 * @param string $bundle
 *   The bundle that was just deleted.
 */
function hook_entity_bundle_delete($entity_type_id, $bundle): void {
  // Remove the settings associated with the bundle in my_module.settings.
  $config = \Drupal::config('my_module.settings');
  $bundle_settings = $config->get('bundle_settings');
  if (isset($bundle_settings[$entity_type_id][$bundle])) {
    unset($bundle_settings[$entity_type_id][$bundle]);
    $config->set('bundle_settings', $bundle_settings);
  }
}

hook_entity_create

/**
 * Acts when creating a new entity.
 *
 * This hook runs after a new entity object has been instantiated, but before
 * it is stored in the database. To react to an entity being stored for the
 * first time, use hook_entity_insert().
 *
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The entity object.
 *
 * @see hook_ENTITY_TYPE_create()
 */
function hook_entity_create(\Drupal\Core\Entity\EntityInterface $entity): void {
  \Drupal::logger('example')->info('Entity created: @label', ['@label' => $entity->label()]);
}

hook_ENTITY_TYPE_create

/**
 * Acts when creating a new entity of a specific type.
 *
 * This hook runs after a new entity object has been instantiated, but before
 * it is stored in the database. To react to an entity being stored for the
 * first time, use hook_entity_insert().
 *
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The entity object.
 *
 * @see hook_entity_create()
 */
function hook_ENTITY_TYPE_create(\Drupal\Core\Entity\EntityInterface $entity): void {
  \Drupal::logger('example')->info('ENTITY_TYPE created: @label', ['@label' => $entity->label()]);
}

hook_entity_duplicate

/**
 * Acts when duplicating an existing entity.
 *
 * @param \Drupal\Core\Entity\EntityInterface $duplicate
 *   The duplicated entity object.
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The original entity object.
 *
 * @see hook_ENTITY_TYPE_duplicate()
 */
function hook_entity_duplicate(\Drupal\Core\Entity\EntityInterface $duplicate, \Drupal\Core\Entity\EntityInterface $entity): void {
  \Drupal::logger('example')->info('Entity duplicated: @label', ['@label' => $entity->label()]);
}

hook_ENTITY_TYPE_duplicate

/**
 * Acts when duplicating an existing entity of a specific type.
 *
 * @param \Drupal\Core\Entity\EntityInterface $duplicate
 *   The duplicated entity object.
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The original entity object.
 *
 * @see hook_entity_duplicate()
 */
function hook_ENTITY_TYPE_duplicate(\Drupal\Core\Entity\EntityInterface $duplicate, \Drupal\Core\Entity\EntityInterface $entity): void {
  \Drupal::logger('example')->info('ENTITY_TYPE duplicated: @label', ['@label' => $entity->label()]);
}

hook_entity_revision_create

/**
 * Respond to entity revision creation.
 *
 * @param \Drupal\Core\Entity\EntityInterface $new_revision
 *   The new revision that was created.
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The original entity that was used to create the revision from.
 * @param bool|null $keep_untranslatable_fields
 *   Whether untranslatable field values were kept (TRUE) or copied from the
 *   default revision (FALSE) when generating a merged revision. If no value was
 *   explicitly specified (NULL), a default value of TRUE should be assumed if
 *   the provided entity is the default translation and untranslatable fields
 *   should only affect the default translation, FALSE otherwise.
 *
 * @see \Drupal\Core\Entity\RevisionableStorageInterface::createRevision()
 * @see \Drupal\Core\Entity\TranslatableRevisionableStorageInterface::createRevision()
 */
function hook_entity_revision_create(\Drupal\Core\Entity\EntityInterface $new_revision, \Drupal\Core\Entity\EntityInterface $entity, $keep_untranslatable_fields): void {
  // Retain the value from an untranslatable field, which are by default
  // synchronized from the default revision.
  $new_revision->set('untranslatable_field', $entity->get('untranslatable_field'));
}

hook_ENTITY_TYPE_revision_create

/**
 * Respond to entity revision creation.
 *
 * @param \Drupal\Core\Entity\EntityInterface $new_revision
 *   The new revision that was created.
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The original entity that was used to create the revision from.
 * @param bool|null $keep_untranslatable_fields
 *   Whether untranslatable field values were kept (TRUE) or copied from the
 *   default revision (FALSE) when generating a merged revision. If no value was
 *   explicitly specified (NULL), a default value of TRUE should be assumed if
 *   the provided entity is the default translation and untranslatable fields
 *   should only affect the default translation, FALSE otherwise.
 *
 * @see \Drupal\Core\Entity\RevisionableStorageInterface::createRevision()
 * @see \Drupal\Core\Entity\TranslatableRevisionableStorageInterface::createRevision()
 */
function hook_ENTITY_TYPE_revision_create(\Drupal\Core\Entity\EntityInterface $new_revision, \Drupal\Core\Entity\EntityInterface $entity, $keep_untranslatable_fields): void {
  // Retain the value from an untranslatable field, which are by default
  // synchronized from the default revision.
  $new_revision->set('untranslatable_field', $entity->get('untranslatable_field'));
}

hook_entity_preload

/**
 * Act on an array of entity IDs before they are loaded.
 *
 * This hook can be used by modules that need, for example, to return a
 * different revision than the default one.
 *
 * @param array $ids
 *   An array of entity IDs that have to be loaded.
 * @param string $entity_type_id
 *   The type of entities being loaded (i.e. node, user, comment).
 *
 * @return \Drupal\Core\Entity\EntityInterface[]
 *   An array of pre-loaded entity objects.
 */
function hook_entity_preload(array $ids, $entity_type_id): array {
  $entities = [];

  foreach ($ids as $id) {
    $entities[] = my_module_swap_revision($id);
  }

  return $entities;
}

hook_entity_load

/**
 * Act on entities when loaded.
 *
 * This is a generic load hook called for all entity types loaded via the
 * entity API.
 *
 * hook_entity_storage_load() should be used to load additional data for
 * content entities.
 *
 * @param \Drupal\Core\Entity\EntityInterface[] $entities
 *   The entities keyed by entity ID.
 * @param string $entity_type_id
 *   The type of entities being loaded (i.e. node, user, comment).
 *
 * @see hook_ENTITY_TYPE_load()
 */
function hook_entity_load(array $entities, $entity_type_id): void {
  foreach ($entities as $entity) {
    $entity->foo = my_module_add_something($entity);
  }
}

hook_ENTITY_TYPE_load

/**
 * Act on entities of a specific type when loaded.
 *
 * @param array $entities
 *   The entities keyed by entity ID.
 *
 * @see hook_entity_load()
 */
function hook_ENTITY_TYPE_load($entities): void {
  foreach ($entities as $entity) {
    $entity->foo = my_module_add_something($entity);
  }
}

hook_entity_storage_load

/**
 * Act on content entities when loaded from the storage.
 *
 * The results of this hook will be cached.
 *
 * @param \Drupal\Core\Entity\EntityInterface[] $entities
 *   The entities keyed by entity ID.
 * @param string $entity_type
 *   The type of entities being loaded (i.e. node, user, comment).
 *
 * @see hook_entity_load()
 */
function hook_entity_storage_load(array $entities, $entity_type): void {
  foreach ($entities as $entity) {
    $entity->foo = my_module_add_something_uncached($entity);
  }
}

hook_ENTITY_TYPE_storage_load

/**
 * Act on content entities of a given type when loaded from the storage.
 *
 * The results of this hook will be cached if the entity type supports it.
 *
 * @param \Drupal\Core\Entity\EntityInterface[] $entities
 *   The entities keyed by entity ID.
 *
 * @see hook_entity_storage_load()
 */
function hook_ENTITY_TYPE_storage_load(array $entities) {
  foreach ($entities as $entity) {
    $entity->foo = my_module_add_something_uncached($entity);
  }
}

hook_entity_presave

/**
 * Act on an entity before it is created or updated.
 *
 * You can get the original entity object from
 * $entity->getOriginal() when it is an update of the entity.
 *
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The entity object.
 *
 * @see hook_ENTITY_TYPE_presave()
 */
function hook_entity_presave(\Drupal\Core\Entity\EntityInterface $entity): void {
  if ($entity instanceof ContentEntityInterface && $entity->isTranslatable()) {
    $route_match = \Drupal::routeMatch();
    \Drupal::service('content_translation.synchronizer')->synchronizeFields($entity, $entity->language()->getId(), $route_match->getParameter('source_langcode'));
  }
}

hook_ENTITY_TYPE_presave

/**
 * Act on a specific type of entity before it is created or updated.
 *
 * You can get the original entity object from
 * $entity->getOriginal() when it is an update of the entity.
 *
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The entity object.
 *
 * @see hook_entity_presave()
 */
function hook_ENTITY_TYPE_presave(\Drupal\Core\Entity\EntityInterface $entity): void {
  if ($entity->isTranslatable()) {
    $route_match = \Drupal::routeMatch();
    \Drupal::service('content_translation.synchronizer')->synchronizeFields($entity, $entity->language()->getId(), $route_match->getParameter('source_langcode'));
  }
}

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.
 *
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The entity object.
 *
 * @see hook_ENTITY_TYPE_insert()
 */
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();
}

hook_ENTITY_TYPE_insert

/**
 * Respond to creation of a new entity of a particular type.
 *
 * This hook runs once the entity has been stored. Note that hook
 * implementations may not alter the stored entity data.
 *
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The entity object.
 *
 * @see hook_entity_insert()
 */
function hook_ENTITY_TYPE_insert(\Drupal\Core\Entity\EntityInterface $entity): void {
  // Insert the new entity into a fictional table of this type of entity.
  \Drupal::database()->insert('example_entity')
    ->fields([
      'id' => $entity->id(),
      'created' => \Drupal::time()->getRequestTime(),
      'updated' => \Drupal::time()->getRequestTime(),
    ])
    ->execute();
}

hook_entity_update

/**
 * Respond to updates to an entity.
 *
 * This hook runs once the entity storage has been updated. Note that hook
 * implementations may not alter the stored entity data. Get the original entity
 * object from $entity->getOriginal().
 *
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The entity object.
 *
 * @see hook_ENTITY_TYPE_update()
 */
function hook_entity_update(\Drupal\Core\Entity\EntityInterface $entity): void {
  // Update the entity's entry in a fictional table of all entities.
  \Drupal::database()->update('example_entity')
    ->fields([
      'updated' => \Drupal::time()->getRequestTime(),
    ])
    ->condition('type', $entity->getEntityTypeId())
    ->condition('id', $entity->id())
    ->execute();
}

hook_ENTITY_TYPE_update

/**
 * Respond to updates to an entity of a particular type.
 *
 * This hook runs once the entity storage has been updated. Note that hook
 * implementations may not alter the stored entity data. Get the original entity
 * object from $entity->getOriginal().
 *
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The entity object.
 *
 * @see hook_entity_update()
 */
function hook_ENTITY_TYPE_update(\Drupal\Core\Entity\EntityInterface $entity): void {
  // Update the entity's entry in a fictional table of this type of entity.
  \Drupal::database()->update('example_entity')
    ->fields([
      'updated' => \Drupal::time()->getRequestTime(),
    ])
    ->condition('id', $entity->id())
    ->execute();
}

hook_entity_translation_create

/**
 * Acts when creating a new entity translation.
 *
 * This hook runs after a new entity translation object has just been
 * instantiated.
 *
 * @param \Drupal\Core\Entity\EntityInterface $translation
 *   The entity object.
 *
 * @see hook_ENTITY_TYPE_translation_create()
 */
function hook_entity_translation_create(\Drupal\Core\Entity\EntityInterface $translation): void {
  \Drupal::logger('example')->info('Entity translation created: @label', ['@label' => $translation->label()]);
}

hook_ENTITY_TYPE_translation_create

/**
 * Acts when creating a new entity translation of a specific type.
 *
 * This hook runs after a new entity translation object has just been
 * instantiated.
 *
 * @param \Drupal\Core\Entity\EntityInterface $translation
 *   The entity object.
 *
 * @see hook_entity_translation_create()
 */
function hook_ENTITY_TYPE_translation_create(\Drupal\Core\Entity\EntityInterface $translation): void {
  \Drupal::logger('example')->info('ENTITY_TYPE translation created: @label', ['@label' => $translation->label()]);
}

hook_entity_translation_insert

/**
 * Respond to creation of a new entity translation.
 *
 * This hook runs once the entity translation has been stored. Note that hook
 * implementations may not alter the stored entity translation data.
 *
 * @param \Drupal\Core\Entity\EntityInterface $translation
 *   The entity object of the translation just stored.
 *
 * @see hook_ENTITY_TYPE_translation_insert()
 */
function hook_entity_translation_insert(\Drupal\Core\Entity\EntityInterface $translation): void {
  $variables = [
    '@language' => $translation->language()->getName(),
    '@label' => $translation->getUntranslated()->label(),
  ];
  \Drupal::logger('example')->notice('The @language translation of @label has just been stored.', $variables);
}

hook_ENTITY_TYPE_translation_insert

/**
 * Respond to creation of a new entity translation of a particular type.
 *
 * This hook runs once the entity translation has been stored. Note that hook
 * implementations may not alter the stored entity translation data.
 *
 * @param \Drupal\Core\Entity\EntityInterface $translation
 *   The entity object of the translation just stored.
 *
 * @see hook_entity_translation_insert()
 */
function hook_ENTITY_TYPE_translation_insert(\Drupal\Core\Entity\EntityInterface $translation): void {
  $variables = [
    '@language' => $translation->language()->getName(),
    '@label' => $translation->getUntranslated()->label(),
  ];
  \Drupal::logger('example')->notice('The @language translation of @label has just been stored.', $variables);
}

hook_entity_translation_delete

/**
 * Respond to entity translation deletion.
 *
 * This hook runs once the entity translation has been deleted from storage.
 *
 * @param \Drupal\Core\Entity\EntityInterface $translation
 *   The original entity object.
 *
 * @see hook_ENTITY_TYPE_translation_delete()
 */
function hook_entity_translation_delete(\Drupal\Core\Entity\EntityInterface $translation): void {
  $variables = [
    '@language' => $translation->language()->getName(),
    '@label' => $translation->label(),
  ];
  \Drupal::logger('example')->notice('The @language translation of @label has just been deleted.', $variables);
}

hook_ENTITY_TYPE_translation_delete

/**
 * Respond to entity translation deletion of a particular type.
 *
 * This hook runs once the entity translation has been deleted from storage.
 *
 * @param \Drupal\Core\Entity\EntityInterface $translation
 *   The original entity object.
 *
 * @see hook_entity_translation_delete()
 */
function hook_ENTITY_TYPE_translation_delete(\Drupal\Core\Entity\EntityInterface $translation): void {
  $variables = [
    '@language' => $translation->language()->getName(),
    '@label' => $translation->label(),
  ];
  \Drupal::logger('example')->notice('The @language translation of @label has just been deleted.', $variables);
}

hook_entity_predelete

/**
 * Act before entity deletion.
 *
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The entity object for the entity that is about to be deleted.
 *
 * @see hook_ENTITY_TYPE_predelete()
 */
function hook_entity_predelete(\Drupal\Core\Entity\EntityInterface $entity): void {
  $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->upsert('example_deleted_entity_statistics')
    ->key(['type', 'id'])
    ->fields([
      'type' => $type,
      'id' => $id,
      'count' => $count,
    ])
    ->execute();
}

hook_ENTITY_TYPE_predelete

/**
 * Act before entity deletion of a particular entity type.
 *
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The entity object for the entity that is about to be deleted.
 *
 * @see hook_entity_predelete()
 */
function hook_ENTITY_TYPE_predelete(\Drupal\Core\Entity\EntityInterface $entity): void {
  $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->upsert('example_deleted_entity_statistics')
    ->key(['type', 'id'])
    ->fields([
      'type' => $type,
      'id' => $id,
      'count' => $count,
    ])
    ->execute();
}

hook_entity_delete

/**
 * Respond to entity deletion.
 *
 * This hook runs once the entity has been deleted from the storage.
 *
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The entity object for the entity that has been deleted.
 *
 * @see hook_ENTITY_TYPE_delete()
 */
function hook_entity_delete(\Drupal\Core\Entity\EntityInterface $entity): void {
  // Delete the entity's entry from a fictional table of all entities.
  \Drupal::database()->delete('example_entity')
    ->condition('type', $entity->getEntityTypeId())
    ->condition('id', $entity->id())
    ->execute();
}

hook_ENTITY_TYPE_delete

/**
 * Respond to entity deletion of a particular type.
 *
 * This hook runs once the entity has been deleted from the storage.
 *
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The entity object for the entity that has been deleted.
 *
 * @see hook_entity_delete()
 */
function hook_ENTITY_TYPE_delete(\Drupal\Core\Entity\EntityInterface $entity): void {
  // Delete the entity's entry from a fictional table of all entities.
  \Drupal::database()->delete('example_entity')
    ->condition('type', $entity->getEntityTypeId())
    ->condition('id', $entity->id())
    ->execute();
}

hook_entity_revision_delete

/**
 * Respond to entity revision deletion.
 *
 * This hook runs once the entity revision has been deleted from the storage.
 *
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The entity object for the entity revision that has been deleted.
 *
 * @see hook_ENTITY_TYPE_revision_delete()
 */
function hook_entity_revision_delete(\Drupal\Core\Entity\EntityInterface $entity): void {
  \Drupal::messenger()->addStatus(t('Deleted revision @revision from @type entity type', [
    '@revision' => $entity->getRevisionId(),
    '@type' => $entity->getEntityType()->getLabel(),
  ]));
}

hook_ENTITY_TYPE_revision_delete

/**
 * Respond to entity revision deletion of a particular type.
 *
 * This hook runs once the entity revision has been deleted from the storage.
 *
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The entity object for the entity revision that has been deleted.
 *
 * @see hook_entity_revision_delete()
 */
function hook_ENTITY_TYPE_revision_delete(\Drupal\Core\Entity\EntityInterface $entity): void {
  \Drupal::messenger()->addStatus(t('Deleted revision @revision from Content entity type', [
    '@revision' => $entity->getRevisionId(),
  ]));
}

hook_entity_view

/**
 * Act on entities being assembled before rendering.
 *
 * @param array &$build
 *   A renderable array representing the entity content. The module may add
 *   elements to $build prior to rendering. The structure of $build is a
 *   renderable array as expected by
 *   \Drupal\Core\Render\RendererInterface::render().
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The entity object.
 * @param \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display
 *   The entity view display holding the display options configured for the
 *   entity components.
 * @param string $view_mode
 *   The view mode the entity is rendered in.
 *
 * @see hook_entity_view_alter()
 * @see hook_ENTITY_TYPE_view()
 */
function hook_entity_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode): void {
  // Only do the extra work if the component is configured to be displayed.
  // This assumes a 'my_module_addition' extra field has been defined for the
  // entity bundle in hook_entity_extra_field_info().
  if ($display->getComponent('my_module_addition')) {
    $build['my_module_addition'] = [
      '#markup' => my_module_addition($entity),
      '#theme' => 'my_module_my_additional_field',
    ];
  }
}

hook_ENTITY_TYPE_view

/**
 * Act on entities of a particular type being assembled before rendering.
 *
 * @param array &$build
 *   A renderable array representing the entity content. The module may add
 *   elements to $build prior to rendering. The structure of $build is a
 *   renderable array as expected by
 *   \Drupal\Core\Render\RendererInterface::render().
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The entity object.
 * @param \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display
 *   The entity view display holding the display options configured for the
 *   entity components.
 * @param string $view_mode
 *   The view mode the entity is rendered in.
 *
 * @see hook_ENTITY_TYPE_view_alter()
 * @see hook_entity_view()
 */
function hook_ENTITY_TYPE_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode): void {
  // Only do the extra work if the component is configured to be displayed.
  // This assumes a 'my_module_addition' extra field has been defined for the
  // entity bundle in hook_entity_extra_field_info().
  if ($display->getComponent('my_module_addition')) {
    $build['my_module_addition'] = [
      '#markup' => my_module_addition($entity),
      '#theme' => 'my_module_my_additional_field',
    ];
  }
}

hook_entity_view_alter

/**
 * Alter the results of the entity build array.
 *
 * This hook is called after the content has been assembled in a structured
 * array and may be used for doing processing which requires that the complete
 * entity content structure has been built.
 *
 * If a module wishes to act on the rendered HTML of the entity rather than the
 * structured content array, it may use this hook to add a #post_render
 * callback. Alternatively, it could also implement hook_preprocess_HOOK() for
 * the particular entity type template, if there is one (e.g., node.html.twig).
 *
 * See the Default theme implementations documentation and
 * \Drupal\Core\Render\RendererInterface::render() for details.
 *
 * @param array &$build
 *   A renderable array representing the entity content.
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The entity object being rendered.
 * @param \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display
 *   The entity view display holding the display options configured for the
 *   entity components.
 *
 * @see hook_entity_view()
 * @see hook_ENTITY_TYPE_view_alter()
 */
function hook_entity_view_alter(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display): void {
  if ($build['#view_mode'] == 'full' && isset($build['an_additional_field'])) {
    // Change its weight.
    $build['an_additional_field']['#weight'] = -10;

    // Add a #post_render callback to act on the rendered HTML of the entity.
    // The object must implement \Drupal\Core\Security\TrustedCallbackInterface.
    $build['#post_render'][] = '\Drupal\my_module\NodeCallback::postRender';
  }
}

hook_ENTITY_TYPE_view_alter

/**
 * Alter the results of the entity build array for a particular entity type.
 *
 * This hook is called after the content has been assembled in a structured
 * array and may be used for doing processing which requires that the complete
 * entity content structure has been built.
 *
 * If a module wishes to act on the rendered HTML of the entity rather than the
 * structured content array, it may use this hook to add a #post_render
 * callback. Alternatively, it could also implement hook_preprocess_HOOK() for
 * the particular entity type template, if there is one (e.g., node.html.twig).
 *
 * See the Default theme implementations documentation and
 * \Drupal\Core\Render\RendererInterface::render() for details.
 *
 * @param array &$build
 *   A renderable array representing the entity content.
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The entity object being rendered.
 * @param \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display
 *   The entity view display holding the display options configured for the
 *   entity components.
 *
 * @see hook_ENTITY_TYPE_view()
 * @see hook_entity_view_alter()
 */
function hook_ENTITY_TYPE_view_alter(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display): void {
  if ($build['#view_mode'] == 'full' && isset($build['an_additional_field'])) {
    // Change its weight.
    $build['an_additional_field']['#weight'] = -10;

    // Add a #post_render callback to act on the rendered HTML of the entity.
    $build['#post_render'][] = 'my_module_node_post_render';
  }
}

hook_entity_prepare_view

/**
 * Act on entities as they are being prepared for view.
 *
 * Allows you to operate on multiple entities as they are being prepared for
 * view. Only use this if attaching the data during the entity loading phase
 * is not appropriate, for example when attaching other 'entity' style objects.
 *
 * @param string $entity_type_id
 *   The type of entities being viewed (i.e. node, user, comment).
 * @param array $entities
 *   The entities keyed by entity ID.
 * @param \Drupal\Core\Entity\Display\EntityViewDisplayInterface[] $displays
 *   The array of entity view displays holding the display options configured
 *   for the entity components, keyed by bundle name.
 * @param string $view_mode
 *   The view mode.
 */
function hook_entity_prepare_view($entity_type_id, array $entities, array $displays, $view_mode): void {
  // Load a specific node into the user object for later theming.
  if (!empty($entities) && $entity_type_id == 'user') {
    // Only do the extra work if the component is configured to be
    // displayed. This assumes a 'my_module_addition' extra field has been
    // defined for the entity bundle in hook_entity_extra_field_info().
    $ids = [];
    foreach ($entities as $id => $entity) {
      if ($displays[$entity->bundle()]->getComponent('my_module_addition')) {
        $ids[] = $id;
      }
    }
    if ($ids) {
      $nodes = my_module_get_user_nodes($ids);
      foreach ($ids as $id) {
        $entities[$id]->user_node = $nodes[$id];
      }
    }
  }
}

hook_entity_view_mode_alter

/**
 * Change the view mode of an entity that is being displayed.
 *
 * @param string $view_mode
 *   The view_mode that is to be used to display the entity.
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The entity that is being viewed.
 *
 */
function hook_entity_view_mode_alter(&$view_mode, \Drupal\Core\Entity\EntityInterface $entity): void {
  // For nodes, change the view mode when it is teaser.
  if ($entity->getEntityTypeId() == 'node' && $view_mode == 'teaser') {
    $view_mode = 'my_custom_view_mode';
  }
}

hook_ENTITY_TYPE_view_mode_alter

/**
 * Change the view mode of a specific entity type currently being displayed.
 *
 * @param string $view_mode
 *   The view_mode currently displaying the entity.
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The entity that is being viewed.
 */
function hook_ENTITY_TYPE_view_mode_alter(string &$view_mode, \Drupal\Core\Entity\EntityInterface $entity): void {
  // Change the view mode to teaser.
  if ($view_mode == 'full') {
    $view_mode = 'teaser';
  }
}

hook_ENTITY_TYPE_build_defaults_alter

/**
 * Alter entity renderable values before cache checking during rendering.
 *
 * Invoked for a specific entity type.
 *
 * The values in the #cache key of the renderable array are used to determine if
 * a cache entry exists for the entity's rendered output. Ideally only values
 * that pertain to caching should be altered in this hook.
 *
 * @param array &$build
 *   A renderable array containing the entity's caching and view mode values.
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The entity that is being viewed.
 * @param string $view_mode
 *   The view_mode that is to be used to display the entity.
 *
 * @see \Drupal\Core\Render\RendererInterface::render()
 * @see \Drupal\Core\Entity\EntityViewBuilder
 * @see hook_entity_build_defaults_alter()
 */
function hook_ENTITY_TYPE_build_defaults_alter(array &$build, \Drupal\Core\Entity\EntityInterface $entity, $view_mode): void {

}

hook_entity_build_defaults_alter

/**
 * Alter entity renderable values before cache checking during rendering.
 *
 * The values in the #cache key of the renderable array are used to determine if
 * a cache entry exists for the entity's rendered output. Ideally only values
 * that pertain to caching should be altered in this hook.
 *
 * @param array &$build
 *   A renderable array containing the entity's caching and view mode values.
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The entity that is being viewed.
 * @param string $view_mode
 *   The view_mode that is to be used to display the entity.
 *
 * @see \Drupal\Core\Render\RendererInterface::render()
 * @see \Drupal\Core\Entity\EntityViewBuilder
 * @see hook_ENTITY_TYPE_build_defaults_alter()
 */
function hook_entity_build_defaults_alter(array &$build, \Drupal\Core\Entity\EntityInterface $entity, $view_mode): void {

}

hook_entity_view_display_alter

/**
 * Alter the settings used for displaying an entity.
 *
 * @param \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display
 *   The entity view display that will be used to display the entity
 *   components.
 * @param array $context
 *   An associative array containing:
 *   - entity_type: The entity type, e.g., 'node' or 'user'.
 *   - bundle: The bundle, e.g., 'page' or 'article'.
 *   - view_mode: The view mode, e.g., 'full', 'teaser', etc.
 */
function hook_entity_view_display_alter(\Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, array $context): void {
  // Hide field labels when displaying nodes in teaser view mode.
  if ($context['entity_type'] == 'node' && $context['view_mode'] == 'teaser') {
    foreach ($display->getComponents() as $name => $options) {
      if (isset($options['label'])) {
        $options['label'] = 'hidden';
        $display->setComponent($name, $options);
      }
    }
  }
}

hook_entity_display_build_alter

/**
 * Alter the render array generated by an EntityDisplay for an entity.
 *
 * @param array $build
 *   The renderable array generated by the EntityDisplay.
 * @param array $context
 *   An associative array containing:
 *   - entity: The entity being rendered.
 *   - view_mode: The view mode; for example, 'full' or 'teaser'.
 *   - display: The EntityDisplay holding the display options.
 */
function hook_entity_display_build_alter(&$build, $context): void {
  /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
  $entity = $context['entity'];
  if ($entity->getEntityTypeId() === 'my_entity' && $entity->bundle() === 'display_build_alter_bundle') {
    $build['entity_display_build_alter']['#markup'] = 'Content added in hook_entity_display_build_alter for entity id ' . $entity->id();
  }
}

hook_entity_prepare_form

/**
 * Acts on an entity object about to be shown on an entity form.
 *
 * This can be typically used to pre-fill entity values or change the form state
 * before the entity form is built. It is invoked just once when first building
 * the entity form. Rebuilds will not trigger a new invocation.
 *
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The entity that is about to be shown on the form.
 * @param string $operation
 *   The current operation.
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 *   The current state of the form.
 *
 * @see \Drupal\Core\Entity\EntityForm::prepareEntity()
 * @see hook_ENTITY_TYPE_prepare_form()
 */
function hook_entity_prepare_form(\Drupal\Core\Entity\EntityInterface $entity, $operation, \Drupal\Core\Form\FormStateInterface $form_state): void {
  if ($operation == 'edit') {
    $entity->label->value = 'Altered label';
    $form_state->set('label_altered', TRUE);
  }
}

hook_ENTITY_TYPE_prepare_form

/**
 * Acts on a particular type of entity object about to be in an entity form.
 *
 * This can be typically used to pre-fill entity values or change the form state
 * before the entity form is built. It is invoked just once when first building
 * the entity form. Rebuilds will not trigger a new invocation.
 *
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The entity that is about to be shown on the form.
 * @param string $operation
 *   The current operation.
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 *   The current state of the form.
 *
 * @see \Drupal\Core\Entity\EntityForm::prepareEntity()
 * @see hook_entity_prepare_form()
 */
function hook_ENTITY_TYPE_prepare_form(\Drupal\Core\Entity\EntityInterface $entity, $operation, \Drupal\Core\Form\FormStateInterface $form_state): void {
  if ($operation == 'edit') {
    $entity->label->value = 'Altered label';
    $form_state->set('label_altered', TRUE);
  }
}

hook_entity_form_mode_alter

/**
 * Change the form mode used to build an entity form.
 *
 * @param string $form_mode
 *   The form_mode that is to be used to build the entity form.
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The entity for which the form is being built.
 */
function hook_entity_form_mode_alter(&$form_mode, \Drupal\Core\Entity\EntityInterface $entity): void {
  // Change the form mode for users with Administrator role.
  if ($entity->getEntityTypeId() == 'user' && $entity->hasRole('administrator')) {
    $form_mode = 'my_custom_form_mode';
  }
}

hook_ENTITY_TYPE_form_mode_alter

/**
 * Change the form mode of a specific entity type currently being displayed.
 *
 * @param string $form_mode
 *   The form_mode currently displaying the entity.
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The entity that is being viewed.
 */
function hook_ENTITY_TYPE_form_mode_alter(string &$form_mode, \Drupal\Core\Entity\EntityInterface $entity): void {
  // Change the form mode for nodes with 'article' bundle.
  if ($entity->bundle() == 'article') {
    $form_mode = 'custom_article_form_mode';
  }
}

hook_entity_form_display_alter

/**
 * Alter the settings used for displaying an entity form.
 *
 * @param \Drupal\Core\Entity\Display\EntityFormDisplayInterface $form_display
 *   The entity_form_display object that will be used to display the entity form
 *   components.
 * @param array $context
 *   An associative array containing:
 *   - entity_type: The entity type, e.g., 'node' or 'user'.
 *   - bundle: The bundle, e.g., 'page' or 'article'.
 *   - form_mode: The form mode; e.g., 'default', 'profile', 'register', etc.
 */
function hook_entity_form_display_alter(\Drupal\Core\Entity\Display\EntityFormDisplayInterface $form_display, array $context): void {
  // Hide the 'user_picture' field from the register form.
  if ($context['entity_type'] == 'user' && $context['form_mode'] == 'register') {
    $form_display->setComponent('user_picture', [
      'region' => 'hidden',
    ]);
  }
}

hook_entity_base_field_info

/**
 * Provides custom base field definitions for a content entity type.
 *
 * Field (storage) definitions returned by this hook must run through the
 * regular field storage life-cycle operations: they need to be properly
 * installed, updated, and uninstalled. This would typically be done through the
 * Entity Update API provided by the entity definition update manager.
 *
 * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
 *   The entity type definition.
 *
 * @return \Drupal\Core\Field\FieldDefinitionInterface[]
 *   An array of field definitions, keyed by field name.
 *
 * @see hook_entity_base_field_info_alter()
 * @see hook_entity_bundle_field_info()
 * @see hook_entity_bundle_field_info_alter()
 * @see \Drupal\Core\Field\FieldDefinitionInterface
 * @see \Drupal\Core\Entity\EntityFieldManagerInterface::getFieldDefinitions()
 * @see \Drupal\Core\Entity\EntityDefinitionUpdateManagerInterface
 * @see https://www.drupal.org/node/3034742
 */
function hook_entity_base_field_info(\Drupal\Core\Entity\EntityTypeInterface $entity_type): array {
  $fields = [];
  if ($entity_type->id() == 'node') {
    $fields['my_module_text'] = BaseFieldDefinition::create('string')
      ->setLabel(t('The text'))
      ->setDescription(t('A text property added by my_module.'))
      ->setComputed(TRUE)
      ->setClass('\Drupal\my_module\EntityComputedText');

  }
  return $fields;
}

hook_entity_base_field_info_alter

/**
 * Alter base field definitions for a content entity type.
 *
 * @param \Drupal\Core\Field\FieldDefinitionInterface[] $fields
 *   The array of base field definitions for the entity type.
 * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
 *   The entity type definition.
 *
 * @see hook_entity_base_field_info()
 * @see hook_entity_bundle_field_info()
 * @see hook_entity_bundle_field_info_alter()
 *
 * @todo WARNING: This hook will be changed in
 * https://www.drupal.org/node/2346329.
 */
function hook_entity_base_field_info_alter(&$fields, \Drupal\Core\Entity\EntityTypeInterface $entity_type) {
  // Alter the my_module_text field to use a custom class.
  if ($entity_type->id() == 'node' && !empty($fields['my_module_text'])) {
    $fields['my_module_text']->setClass('\Drupal\another_module\EntityComputedText');
  }
}

hook_entity_bundle_field_info

/**
 * Provides field definitions for a specific bundle within an entity type.
 *
 * Bundle fields either have to override an existing base field, or need to
 * provide a field storage definition via hook_entity_field_storage_info()
 * unless they are computed.
 *
 * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
 *   The entity type definition.
 * @param string $bundle
 *   The bundle.
 * @param \Drupal\Core\Field\FieldDefinitionInterface[] $base_field_definitions
 *   The list of base field definitions for the entity type.
 *
 * @return \Drupal\Core\Field\FieldDefinitionInterface[]
 *   An array of bundle field definitions, keyed by field name.
 *
 * @see hook_entity_base_field_info()
 * @see hook_entity_base_field_info_alter()
 * @see hook_entity_field_storage_info()
 * @see hook_entity_field_storage_info_alter()
 * @see hook_entity_bundle_field_info_alter()
 * @see \Drupal\Core\Field\FieldDefinitionInterface
 * @see \Drupal\Core\Field\FieldDefinition
 * @see \Drupal\Core\Entity\EntityFieldManagerInterface::getFieldDefinitions()
 *
 * @todo WARNING: This hook will be changed in
 * https://www.drupal.org/node/2346347.
 */
function hook_entity_bundle_field_info(\Drupal\Core\Entity\EntityTypeInterface $entity_type, $bundle, array $base_field_definitions): array {
  $fields = [];
  // Add a property only to nodes of the 'article' bundle.
  if ($entity_type->id() == 'node' && $bundle == 'article') {
    $storage_definitions = my_module_entity_field_storage_info($entity_type);
    $fields['my_module_bundle_field'] = FieldDefinition::createFromFieldStorageDefinition($storage_definitions['my_module_bundle_field'])
      ->setLabel(t('Bundle Field'));
  }
  return $fields;
}

hook_entity_bundle_field_info_alter

/**
 * Alter bundle field definitions.
 *
 * @param \Drupal\Core\Field\FieldDefinitionInterface[] $fields
 *   The array of bundle field definitions.
 * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
 *   The entity type definition.
 * @param string $bundle
 *   The bundle.
 *
 * @see hook_entity_base_field_info()
 * @see hook_entity_base_field_info_alter()
 * @see hook_entity_bundle_field_info()
 *
 * @todo WARNING: This hook will be changed in
 * https://www.drupal.org/node/2346347.
 */
function hook_entity_bundle_field_info_alter(&$fields, \Drupal\Core\Entity\EntityTypeInterface $entity_type, $bundle) {
  if ($entity_type->id() == 'node' && $bundle == 'article' && !empty($fields['my_module_text'])) {
    // Alter the my_module_text field to use a custom class.
    $fields['my_module_text']->setClass('\Drupal\another_module\EntityComputedText');
  }
}

hook_entity_field_storage_info

/**
 * Provides field storage definitions for a content entity type.
 *
 * Field storage definitions returned by this hook must run through the regular
 * field storage life-cycle operations: they need to be properly installed,
 * updated, and uninstalled. This would typically be done through the Entity
 * Update API provided by the entity definition update manager.
 *
 * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
 *   The entity type definition.
 *
 * @return \Drupal\Core\Field\FieldStorageDefinitionInterface[]
 *   An array of field storage definitions, keyed by field name.
 *
 * @see hook_entity_field_storage_info_alter()
 * @see \Drupal\Core\Field\FieldStorageDefinitionInterface
 * @see \Drupal\Core\Entity\EntityFieldManagerInterface::getFieldStorageDefinitions()
 * @see \Drupal\Core\Entity\EntityDefinitionUpdateManagerInterface
 * @see https://www.drupal.org/node/3034742
 */
function hook_entity_field_storage_info(\Drupal\Core\Entity\EntityTypeInterface $entity_type): array {
  $result = [];
  if (\Drupal::entityTypeManager()->getStorage($entity_type->id()) instanceof DynamicallyFieldableEntityStorageInterface) {
    // Query by filtering on the ID as this is more efficient than filtering
    // on the entity_type property directly.
    $ids = \Drupal::entityQuery('field_storage_config')
      ->condition('id', $entity_type->id() . '.', 'STARTS_WITH')
      ->execute();
    // Fetch all fields and key them by field name.
    $field_storages = FieldStorageConfig::loadMultiple($ids);
    foreach ($field_storages as $field_storage) {
      $result[$field_storage->getName()] = $field_storage;
    }
  }
  return $result;
}

hook_entity_field_storage_info_alter

/**
 * Alter field storage definitions for a content entity type.
 *
 * @param \Drupal\Core\Field\FieldStorageDefinitionInterface[] $fields
 *   The array of field storage definitions for the entity type.
 * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
 *   The entity type definition.
 *
 * @see hook_entity_field_storage_info()
 */
function hook_entity_field_storage_info_alter(&$fields, \Drupal\Core\Entity\EntityTypeInterface $entity_type) {
  // Alter the max_length setting.
  if ($entity_type->id() == 'node' && !empty($fields['my_module_text'])) {
    $fields['my_module_text']->setSetting('max_length', 128);
  }
}

hook_entity_operation

/**
 * Declares entity operations.
 *
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The entity on which the linked operations will be performed.
 * @param \Drupal\Core\Cache\CacheableMetadata $cacheability
 *   The cacheable metadata to add to if your operations vary by or depend on
 *   something.
 *
 * @return array
 *   An operations array as returned by
 *   EntityListBuilderInterface::getOperations().
 *
 * @see \Drupal\Core\Entity\EntityListBuilderInterface::getOperations()
 */
function hook_entity_operation(\Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Cache\CacheableMetadata $cacheability): array {
  $operations = [];
  $operations['translate'] = [
    'title' => t('Translate'),
    'url' => \Drupal\Core\Url::fromRoute('foo_module.entity.translate'),
    'weight' => 50,
  ];

  return $operations;
}

hook_entity_operation_alter

/**
 * Alter entity operations.
 *
 * @param array $operations
 *   Operations array as returned by
 *   \Drupal\Core\Entity\EntityListBuilderInterface::getOperations().
 * @param \Drupal\Core\Entity\EntityInterface $entity
 *   The entity on which the linked operations will be performed.
 * @param \Drupal\Core\Cache\CacheableMetadata $cacheability
 *   The cacheable metadata to add to if your operations vary by or depend on
 *   something.
 */
function hook_entity_operation_alter(array &$operations, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Cache\CacheableMetadata $cacheability) {
  // Alter the title and weight.
  $operations['translate']['title'] = t('Translate @entity_type', [
    '@entity_type' => $entity->getEntityTypeId(),
  ]);
  $operations['translate']['weight'] = 99;
}

hook_entity_field_access

/**
 * Control access to fields.
 *
 * This hook is invoked from
 * \Drupal\Core\Entity\EntityAccessControlHandler::fieldAccess() to let modules
 * grant or deny operations on fields.
 *
 * @param string $operation
 *   The operation to be performed. See
 *   \Drupal\Core\Entity\EntityAccessControlHandlerInterface::fieldAccess()
 *   for possible values.
 * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
 *   The field definition.
 * @param \Drupal\Core\Session\AccountInterface $account
 *   The user account to check.
 * @param \Drupal\Core\Field\FieldItemListInterface $items
 *   (optional) The entity field object for which to check access, or NULL if
 *   access is checked for the field definition, without any specific value
 *   available. Defaults to NULL.
 *
 * @return \Drupal\Core\Access\AccessResultInterface
 *   The access result.
 *
 * @see \Drupal\Core\Entity\EntityAccessControlHandlerInterface::fieldAccess()
 */
function hook_entity_field_access($operation, \Drupal\Core\Field\FieldDefinitionInterface $field_definition, \Drupal\Core\Session\AccountInterface $account, ?\Drupal\Core\Field\FieldItemListInterface $items = NULL): \Drupal\Core\Access\AccessResultInterface {
  if ($field_definition->getName() == 'field_of_interest' && $operation == 'edit') {
    return AccessResult::allowedIfHasPermission($account, 'update field of interest');
  }
  return AccessResult::neutral();
}

hook_entity_field_access_alter

/**
 * Alter the default access behavior for a given field.
 *
 * Use this hook to override access grants from another module. Note that the
 * original default access flag is masked under the ':default' key.
 *
 * @param \Drupal\Core\Access\AccessResultInterface[] $grants
 *   An array of grants gathered by hook_entity_field_access(). The array is
 *   keyed by the module that defines the field's access control; the values are
 *   grant responses for each module (\Drupal\Core\Access\AccessResult).
 * @param array $context
 *   Context array on the performed operation with the following keys:
 *   - operation: The operation to be performed (string).
 *   - field_definition: The field definition object
 *     (\Drupal\Core\Field\FieldDefinitionInterface)
 *   - account: The user account to check access for
 *     (Drupal\user\Entity\User).
 *   - items: (optional) The entity field items
 *     (\Drupal\Core\Field\FieldItemListInterface).
 */
function hook_entity_field_access_alter(array &$grants, array $context) {
  /** @var \Drupal\Core\Field\FieldDefinitionInterface $field_definition */
  $field_definition = $context['field_definition'];
  if ($field_definition->getName() == 'field_of_interest' && $grants['node']->isForbidden()) {
    // Override node module's restriction to no opinion (neither allowed nor
    // forbidden). We don't want to provide our own access hook, we only want to
    // take out node module's part in the access handling of this field. We also
    // don't want to switch node module's grant to
    // AccessResultInterface::isAllowed() , because the grants of other modules
    // should still decide on their own if this field is accessible or not.
    $grants['node'] = AccessResult::neutral()->inheritCacheability($grants['node']);
  }
}

hook_entity_field_values_init

/**
 * Acts when initializing a fieldable entity object.
 *
 * This hook runs after a new entity object or a new entity translation object
 * has just been instantiated. It can be used to set initial values, e.g. to
 * provide defaults.
 *
 * @param \Drupal\Core\Entity\FieldableEntityInterface $entity
 *   The entity object.
 *
 * @see hook_ENTITY_TYPE_field_values_init()
 */
function hook_entity_field_values_init(\Drupal\Core\Entity\FieldableEntityInterface $entity): void {
  if ($entity instanceof \Drupal\Core\Entity\ContentEntityInterface && !$entity->foo->value) {
    $entity->foo->value = 'some_initial_value';
  }
}

hook_ENTITY_TYPE_field_values_init

/**
 * Acts when initializing a fieldable entity object.
 *
 * This hook runs after a new entity object or a new entity translation object
 * has just been instantiated. It can be used to set initial values, e.g. to
 * provide defaults.
 *
 * @param \Drupal\Core\Entity\FieldableEntityInterface $entity
 *   The entity object.
 *
 * @see hook_entity_field_values_init()
 */
function hook_ENTITY_TYPE_field_values_init(\Drupal\Core\Entity\FieldableEntityInterface $entity): void {
  if (!$entity->foo->value) {
    $entity->foo->value = 'some_initial_value';
  }
}

hook_entity_extra_field_info

/**
 * Exposes "pseudo-field" components on content entities.
 *
 * Field UI's "Manage fields" and "Manage display" pages let users re-order
 * fields, but also non-field components. For nodes, these include elements
 * exposed by modules through hook_form_alter(), for instance.
 *
 * Content entities or modules that want to have their components supported
 * should expose them using this hook. The user-defined settings (weight,
 * visible) are automatically applied when entities or entity forms are
 * rendered.
 *
 * @see hook_entity_extra_field_info_alter()
 *
 * @return array
 *   The array structure is identical to that of the return value of
 *   \Drupal\Core\Entity\EntityFieldManagerInterface::getExtraFields().
 */
function hook_entity_extra_field_info(): array {
  $extra = [];
  $module_language_enabled = \Drupal::moduleHandler()->moduleExists('language');
  $description = t('Node module element');

  foreach (NodeType::loadMultiple() as $bundle) {

    // Add also the 'language' select if Language module is enabled and the
    // bundle has multilingual support.
    // Visibility of the ordering of the language selector is the same as on the
    // node/add form.
    if ($module_language_enabled) {
      $configuration = ContentLanguageSettings::loadByEntityTypeBundle('node', $bundle->id());
      if ($configuration->isLanguageAlterable()) {
        $extra['node'][$bundle->id()]['form']['language'] = [
          'label' => t('Language'),
          'description' => $description,
          'weight' => 0,
        ];
      }
    }
    $extra['node'][$bundle->id()]['display']['language'] = [
      'label' => t('Language'),
      'description' => $description,
      'weight' => 0,
      'visible' => FALSE,
    ];
  }

  return $extra;
}

hook_entity_extra_field_info_alter

/**
 * Alter "pseudo-field" components on content entities.
 *
 * @param array $info
 *   The array structure is identical to that of the return value of
 *   \Drupal\Core\Entity\EntityFieldManagerInterface::getExtraFields().
 *
 * @see hook_entity_extra_field_info()
 */
function hook_entity_extra_field_info_alter(&$info) {
  // Force node title to always be at the top of the list by default.
  foreach (NodeType::loadMultiple() as $bundle) {
    if (isset($info['node'][$bundle->id()]['form']['title'])) {
      $info['node'][$bundle->id()]['form']['title']['weight'] = -20;
    }
  }
}

hook_entity_query_alter

/**
 * Alter an entity query.
 *
 * @param \Drupal\Core\Entity\Query\QueryInterface $query
 *   The entity query.
 *
 * @see hook_entity_query_ENTITY_TYPE_alter()
 * @see hook_entity_query_tag__TAG_alter()
 * @see \Drupal\Core\Entity\Query\QueryInterface
 */
function hook_entity_query_alter(\Drupal\Core\Entity\Query\QueryInterface $query): void {
  if ($query->hasTag('entity_reference')) {
    $entityType = \Drupal::entityTypeManager()->getDefinition($query->getEntityTypeId());
    $query->sort($entityType->getKey('id'), 'desc');
  }
}

hook_entity_query_ENTITY_TYPE_alter

/**
 * Alter an entity query for a specific entity type.
 *
 * @param \Drupal\Core\Entity\Query\QueryInterface $query
 *   The entity query.
 *
 * @see hook_entity_query_alter()
 * @see \Drupal\Core\Entity\Query\QueryInterface
 */
function hook_entity_query_ENTITY_TYPE_alter(\Drupal\Core\Entity\Query\QueryInterface $query): void {
  $query->condition('id', '1', '<>');
}

hook_entity_query_tag__TAG_alter

/**
 * Alter an entity query that has a specific tag.
 *
 * @param \Drupal\Core\Entity\Query\QueryInterface $query
 *   The entity query.
 *
 * @see hook_entity_query_alter()
 * @see hook_entity_query_tag__ENTITY_TYPE__TAG_alter()
 * @see \Drupal\Core\Entity\Query\QueryInterface
 */
function hook_entity_query_tag__TAG_alter(\Drupal\Core\Entity\Query\QueryInterface $query): void {
  $entityType = \Drupal::entityTypeManager()->getDefinition($query->getEntityTypeId());
  $query->sort($entityType->getKey('id'), 'desc');
}

hook_entity_query_tag__ENTITY_TYPE__TAG_alter

/**
 * Alter an entity query for a specific entity type that has a specific tag.
 *
 * @param \Drupal\Core\Entity\Query\QueryInterface $query
 *   The entity query.
 *
 * @see hook_entity_query_ENTITY_TYPE_alter()
 * @see hook_entity_query_tag__TAG_alter()
 * @see \Drupal\Core\Entity\Query\QueryInterface
 */
function hook_entity_query_tag__ENTITY_TYPE__TAG_alter(\Drupal\Core\Entity\Query\QueryInterface $query): void {
  $query->condition('id', '1', '<>');
}

hook_entity_reference_selection_alter

/**
 * Modify the list of available entity reference plugins.
 *
 * This hook may be used to modify plugin properties after they have been
 * specified by other modules.
 *
 * @param array $plugins
 *   An array of all the existing plugin definitions, passed by reference.
 *
 * @see \Drupal\Core\Entity\EntityReferenceSelection\SelectionPluginManager
 */
function hook_entity_reference_selection_alter(array &$plugins): void {
  // Remove a plugin.
  unset($plugins['broken']);
}