You are here

function field_field_config_presave in Drupal 9

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

Implements hook_ENTITY_TYPE_presave() for 'field_config'.

Determine the selection handler plugin ID for an entity reference field.

File

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

Code

function field_field_config_presave(FieldConfigInterface $field) {

  // Don't change anything during a configuration sync.
  if ($field
    ->isSyncing()) {
    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
    ->getType());
  if ($class !== $item_class && !is_subclass_of($class, $item_class)) {
    return;
  }

  // Make sure the selection handler plugin is the correct derivative for the
  // target entity type.
  $target_type = $field
    ->getFieldStorageDefinition()
    ->getSetting('target_type');
  $selection_manager = \Drupal::service('plugin.manager.entity_reference_selection');
  list($current_handler) = explode(':', $field
    ->getSetting('handler'), 2);
  $field
    ->setSetting('handler', $selection_manager
    ->getPluginId($target_type, $current_handler));

  // In case we removed all the target bundles allowed by the field in
  // EntityReferenceItem::onDependencyRemoval() or field_entity_bundle_delete()
  // we have to log a critical message because the field will not function
  // correctly anymore.
  $handler_settings = $field
    ->getSetting('handler_settings');
  if (isset($handler_settings['target_bundles']) && $handler_settings['target_bundles'] === []) {
    \Drupal::logger('entity_reference')
      ->critical('The %field_name entity reference field (entity_type: %entity_type, bundle: %bundle) no longer has any valid bundle it can reference. The field is not working correctly anymore and has to be adjusted.', [
      '%field_name' => $field
        ->getName(),
      '%entity_type' => $field
        ->getTargetEntityTypeId(),
      '%bundle' => $field
        ->getTargetBundle(),
    ]);
  }
}