You are here

function field_field_storage_config_update in Drupal 9

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

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.

File

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

Code

function field_field_storage_config_update(FieldStorageConfigInterface $field_storage) {
  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->original
    ->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();
    }
  }
}