You are here

public function FieldDefinitionListener::onFieldDefinitionDelete in Drupal 8

Same name and namespace in other branches
  1. 9 core/lib/Drupal/Core/Field/FieldDefinitionListener.php \Drupal\Core\Field\FieldDefinitionListener::onFieldDefinitionDelete()

Reacts to the deletion of a field.

Stored values should not be wiped at once, but marked as 'deleted' so that they can go through a proper purge process later on.

Parameters

\Drupal\Core\Field\FieldDefinitionInterface $field_definition: The field definition being deleted.

Overrides FieldDefinitionListenerInterface::onFieldDefinitionDelete

File

core/lib/Drupal/Core/Field/FieldDefinitionListener.php, line 116

Class

FieldDefinitionListener
Reacts to field definition CRUD on behalf of the Entity system.

Namespace

Drupal\Core\Field

Code

public function onFieldDefinitionDelete(FieldDefinitionInterface $field_definition) {
  $entity_type_id = $field_definition
    ->getTargetEntityTypeId();
  $bundle = $field_definition
    ->getTargetBundle();
  $field_name = $field_definition
    ->getName();

  // Notify the storage about the field deletion.
  $this->entityTypeManager
    ->getStorage($entity_type_id)
    ->onFieldDefinitionDelete($field_definition);

  // Unset the bundle from the bundle field map key value collection.
  $bundle_field_map = $this->keyValueFactory
    ->get('entity.definitions.bundle_field_map')
    ->get($entity_type_id);
  unset($bundle_field_map[$field_name]['bundles'][$bundle]);
  if (empty($bundle_field_map[$field_name]['bundles'])) {

    // If there are no bundles left, remove the field from the map.
    unset($bundle_field_map[$field_name]);
  }
  $this->keyValueFactory
    ->get('entity.definitions.bundle_field_map')
    ->set($entity_type_id, $bundle_field_map);

  // Delete the cache entry.
  $this->cacheBackend
    ->delete('entity_field_map');

  // If the field map is initialized, update it as well, so that calls to it
  // do not have to rebuild it again.
  if ($field_map = $this->entityFieldManager
    ->getFieldMap()) {
    unset($field_map[$entity_type_id][$field_name]['bundles'][$bundle]);
    if (empty($field_map[$entity_type_id][$field_name]['bundles'])) {
      unset($field_map[$entity_type_id][$field_name]);
    }
    $this->entityFieldManager
      ->setFieldMap($field_map);
  }
}