function FieldHooks::fieldStorageConfigUpdate

Same name and namespace in other branches
  1. 11.x core/modules/field/src/Hook/FieldHooks.php \Drupal\field\Hook\FieldHooks::fieldStorageConfigUpdate()

Implements hook_ENTITY_TYPE_update() for 'field_storage_config'.

Reset the field handler settings, when the storage target_type is changed on an entity reference field.

Attributes

#[Hook('field_storage_config_update')]

File

core/modules/field/src/Hook/FieldHooks.php, line 352

Class

FieldHooks
Hook implementations for field.

Namespace

Drupal\field\Hook

Code

public function fieldStorageConfigUpdate(FieldStorageConfigInterface $field_storage) : void {
  if ($field_storage->isSyncing()) {
    // Don't change anything during a configuration sync.
    return;
  }
  // Act on all sub-types of the entity_reference field type.
  /** @var \Drupal\Core\Field\FieldTypePluginManager $field_type_manager */
  $field_type_manager = \Drupal::service('plugin.manager.field.field_type');
  $item_class = 'Drupal\\Core\\Field\\Plugin\\Field\\FieldType\\EntityReferenceItem';
  $class = $field_type_manager->getPluginClass($field_storage->getType());
  if ($class !== $item_class && !is_subclass_of($class, $item_class)) {
    return;
  }
  // If target_type changed, reset the handler in the fields using that
  // storage.
  if ($field_storage->getSetting('target_type') !== $field_storage->getOriginal()
    ->getSetting('target_type')) {
    foreach ($field_storage->getBundles() as $bundle) {
      $field = FieldConfig::loadByName($field_storage->getTargetEntityTypeId(), $bundle, $field_storage->getName());
      // Reset the handler settings. This triggers
      // field_field_config_presave(), which will take care of reassigning the
      // handler to the correct derivative for the new target_type.
      $field->setSetting('handler_settings', []);
      $field->save();
    }
  }
}

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