You are here

protected function NameAdditionalPreferredTrait::getAdditionalSources in Name Field 8

Helper function to find attached fields to use as alternative sources.

Currently field items do not support dependencies injected.

To refactor once https://www.drupal.org/node/2053415 gets in.

Return value

array The discovered additional sources.

2 calls to NameAdditionalPreferredTrait::getAdditionalSources()
NameAdditionalPreferredTrait::getNameAdditionalPreferredSettingsForm in src/Traits/NameAdditionalPreferredTrait.php
Returns a form for the default settings defined above.
NameAdditionalPreferredTrait::settingsNameAdditionalPreferredSummary in src/Traits/NameAdditionalPreferredTrait.php

File

src/Traits/NameAdditionalPreferredTrait.php, line 130

Class

NameAdditionalPreferredTrait
Name form for preferred and alternative settings trait.

Namespace

Drupal\name\Traits

Code

protected function getAdditionalSources() {
  if (!isset($this->entityTypeManager)) {
    $this->entityTypeManager = \Drupal::service('entity_type.manager');
  }
  if (!isset($this->entityFieldManager)) {
    $this->entityFieldManager = \Drupal::service('entity_field.manager');
  }

  // If a formatter, $this->fieldDefinition is set, otherwise we have a field.
  $field_definition = empty($this->fieldDefinition) ? $this
    ->getFieldDefinition() : $this->fieldDefinition;
  $entity_type_id = $field_definition
    ->getTargetEntityTypeId();
  $entity_type = $this->entityTypeManager
    ->getStorage($entity_type_id)
    ->getEntityType();
  $bundle = $field_definition
    ->getTargetBundle();
  $entity_type_label = $entity_type
    ->getBundleLabel($bundle);
  if (!$entity_type_label) {
    $entity_type_label = $entity_type
      ->getLabel();
  }
  $sources = [
    '_self' => $this
      ->t('@label label', [
      '@label' => $entity_type_label,
    ]),
  ];
  if ($entity_type_id == 'user') {
    $sources['_self_property_name'] = $this
      ->t('@label login name', [
      '@label' => $entity_type_label,
    ]);
  }
  $fields = $this->entityFieldManager
    ->getFieldDefinitions($entity_type_id, $bundle);
  foreach ($fields as $field_name => $field) {
    if (!$field
      ->getFieldStorageDefinition()
      ->isBaseField() && $field_name != $field_definition
      ->getName()) {
      $sources[$field
        ->getName()] = $field
        ->getLabel();
    }
  }
  return $sources;
}