public function FieldInstance::delete

Overrides \Drupal\Core\Entity\Entity::delete().

Parameters

bool $field_cleanup: (optional) If TRUE, the field will be deleted as well if its last instance is being deleted. If FALSE, it is the caller's responsibility to handle the case of fields left without instances. Defaults to TRUE.

Overrides Entity::delete

File

drupal/core/modules/field/lib/Drupal/field/Plugin/Core/Entity/FieldInstance.php, line 442
Contains \Drupal\field\Plugin\Core\Entity\FieldInstance.

Class

FieldInstance
Defines the Field instance entity.

Namespace

Drupal\field\Plugin\Core\Entity

Code

public function delete($field_cleanup = TRUE) {
  if (!$this->deleted) {
    $module_handler = \Drupal::moduleHandler();
    $state = \Drupal::state();

    // Delete the configuration of this instance and save the configuration
    // in the key_value table so we can use it later during
    // field_purge_batch().
    $deleted_instances = $state
      ->get('field.instance.deleted') ?: array();
    $config = $this
      ->getExportProperties();
    $config['deleted'] = TRUE;
    $deleted_instances[$this->uuid] = $config;
    $state
      ->set('field.instance.deleted', $deleted_instances);
    parent::delete();

    // Clear the cache.
    field_cache_clear();

    // Mark instance data for deletion by invoking
    // hook_field_storage_delete_instance().
    $module_handler
      ->invoke($this->field->storage['module'], 'field_storage_delete_instance', array(
      $this,
    ));

    // Let modules react to the deletion of the instance with
    // hook_field_delete_instance().
    $module_handler
      ->invokeAll('field_delete_instance', array(
      $this,
    ));

    // Remove the instance from the entity form displays.
    if ($form_display = entity_load('entity_form_display', $this->entity_type . '.' . $this->bundle . '.default')) {
      $form_display
        ->removeComponent($this->field
        ->id())
        ->save();
    }

    // Remove the instance from the entity displays.
    $ids = array();
    $view_modes = array(
      'default' => array(),
    ) + entity_get_view_modes($this->entity_type);
    foreach (array_keys($view_modes) as $view_mode) {
      $ids[] = $this->entity_type . '.' . $this->bundle . '.' . $view_mode;
    }
    foreach (entity_load_multiple('entity_display', $ids) as $display) {
      $display
        ->removeComponent($this->field
        ->id())
        ->save();
    }

    // Delete the field itself if we just deleted its last instance.
    if ($field_cleanup && count($this->field
      ->getBundles()) == 0) {
      $this->field
        ->delete();
    }
  }
}