You are here

public function FieldManager::updateExistingReferenceFields in Scheduled Updates 8

Update existing Entity reference fields to have the bundle as a target.

Parameters

array $existing_field_settings:

\Drupal\scheduled_updates\ScheduledUpdateTypeInterface $entity:

Return value

mixed

Overrides FieldManagerInterface::updateExistingReferenceFields

File

src/FieldManager.php, line 198
Contains \Drupal\scheduled_updates\FieldManager.

Class

FieldManager
Field Manager for handling fields for Scheduled Updates.

Namespace

Drupal\scheduled_updates

Code

public function updateExistingReferenceFields(array $existing_field_settings, ScheduledUpdateTypeInterface $scheduled_update_type) {
  $field_id = $existing_field_settings['field_id'];
  $entity_type_id = $scheduled_update_type
    ->getUpdateEntityType();

  /** @var FieldConfig $selected_config_field */
  $selected_config_field = FieldConfig::load($field_id);
  $field_storage = $selected_config_field
    ->getFieldStorageDefinition();
  $config_fields = $this
    ->getAllFieldConfigsForField($field_storage, $scheduled_update_type
    ->getUpdateEntityType());
  $current_bundles = array_keys($config_fields);
  $needed_bundles = array_diff($existing_field_settings['bundles'], $current_bundles);

  /** @var FieldConfig $config_field */
  foreach ($config_fields as $config_field) {
    $settings = $config_field
      ->getSetting('handler_settings');
    $settings['target_bundles'][] = $scheduled_update_type
      ->id();
    $config_field
      ->setSetting('handler_settings', $settings);
    $config_field
      ->save();
  }
  if ($needed_bundles) {
    foreach ($needed_bundles as $needed_bundle) {
      $field_values = [
        'field_name' => $field_storage
          ->getName(),
        'entity_type' => $entity_type_id,
        'bundle' => $needed_bundle,
        'label' => $selected_config_field
          ->label(),
        // Field translatability should be explicitly enabled by the users.
        'translatable' => $selected_config_field
          ->isTranslatable(),
        'settings' => [
          'handler_settings' => [
            'target_bundles' => [
              $scheduled_update_type
                ->id(),
            ],
          ],
        ],
      ];
      $new_field = FieldConfig::create($field_values);
      $new_field
        ->save();
      $this
        ->addToDefaultFormDisplay($entity_type_id, $needed_bundle, $selected_config_field
        ->label(), $field_storage
        ->getName());
    }
  }
}