You are here

function field_entity_bundle_delete in Drupal 8

Same name and namespace in other branches
  1. 9 core/modules/field/field.module \field_entity_bundle_delete()
  2. 10 core/modules/field/field.module \field_entity_bundle_delete()

Implements hook_entity_bundle_delete().

Related topics

File

core/modules/field/field.module, line 217
Attach custom data fields to Drupal entities.

Code

function field_entity_bundle_delete($entity_type_id, $bundle) {
  $storage = \Drupal::entityTypeManager()
    ->getStorage('field_config');

  // Get the fields on the bundle.
  $fields = $storage
    ->loadByProperties([
    'entity_type' => $entity_type_id,
    'bundle' => $bundle,
  ]);

  // This deletes the data for the field as well as the field themselves. This
  // function actually just marks the data and fields as deleted, leaving the
  // garbage collection for a separate process, because it is not always
  // possible to delete this much data in a single page request (particularly
  // since for some field types, the deletion is more than just a simple DELETE
  // query).
  foreach ($fields as $field) {
    $field
      ->delete();
  }

  // We are duplicating the work done by
  // \Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem::onDependencyRemoval()
  // because we need to take into account bundles that are not provided by a
  // config entity type so they are not part of the config dependencies.
  // Gather a list of all entity reference fields.
  $map = \Drupal::service('entity_field.manager')
    ->getFieldMapByFieldType('entity_reference');
  $ids = [];
  foreach ($map as $type => $info) {
    foreach ($info as $name => $data) {
      foreach ($data['bundles'] as $bundle_name) {
        $ids[] = "{$type}.{$bundle_name}.{$name}";
      }
    }
  }

  // Update the 'target_bundles' handler setting if needed.
  foreach (FieldConfig::loadMultiple($ids) as $field_config) {
    if ($field_config
      ->getSetting('target_type') == $entity_type_id) {
      $handler_settings = $field_config
        ->getSetting('handler_settings');
      if (isset($handler_settings['target_bundles'][$bundle])) {
        unset($handler_settings['target_bundles'][$bundle]);
        $field_config
          ->setSetting('handler_settings', $handler_settings);
        $field_config
          ->save();
      }
    }
  }
}