You are here

class NameFormatter in Name Field 8

Same name in this branch
  1. 8 src/NameFormatter.php \Drupal\name\NameFormatter
  2. 8 src/Plugin/Field/FieldFormatter/NameFormatter.php \Drupal\name\Plugin\Field\FieldFormatter\NameFormatter

Plugin implementation of the 'name' formatter.

The 'Default' formatter is different for integer fields on the one hand, and for decimal and float fields on the other hand, in order to be able to use different settings.

Plugin annotation


@FieldFormatter(
  id = "name_default",
  module = "name",
  label = @Translation("Name formatter"),
  field_types = {
    "name",
  }
)

Hierarchy

Expanded class hierarchy of NameFormatter

File

src/Plugin/Field/FieldFormatter/NameFormatter.php, line 37

Namespace

Drupal\name\Plugin\Field\FieldFormatter
View source
class NameFormatter extends FormatterBase implements ContainerFactoryPluginInterface {
  use NameAdditionalPreferredTrait;

  /**
   * The entity field manager.
   *
   * @var \Drupal\Core\Entity\EntityFieldManager
   */
  protected $entityFieldManager;

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The field renderer for any additional components.
   *
   * @var \Drupal\Core\Render\RendererInterface
   */
  protected $renderer;

  /**
   * The name formatter.
   *
   * @var \Drupal\name\NameFormatter
   */
  protected $formatter;

  /**
   * The name format parser.
   *
   * Directly called to format the examples without the fallback.
   *
   * @var \Drupal\name\NameFormatParser
   */
  protected $parser;

  /**
   * The name generator.
   *
   * @var \Drupal\name\NameGeneratorInterface
   */
  protected $generator;

  /**
   * Constructs a NameFormatter instance.
   *
   * @param string $plugin_id
   *   The plugin_id for the formatter.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
   *   The definition of the field to which the formatter is associated.
   * @param array $settings
   *   The formatter settings.
   * @param string $label
   *   The formatter label display setting.
   * @param string $view_mode
   *   The view mode.
   * @param array $third_party_settings
   *   Any third party settings settings.
   * @param \Drupal\Core\Entity\EntityFieldManager $entityFieldManager
   *   The entity field manager.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager
   *   The entity type manager.
   * @param \Drupal\Core\Render\RendererInterface $renderer
   *   The rendering service.
   * @param \Drupal\name\NameFormatter $formatter
   *   The name formatter.
   * @param \Drupal\name\NameFormatParser $parser
   *   The name format parser.
   * @param \Drupal\name\NameGeneratorInterface $generator
   *   The name format parser.
   */
  public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, $label, $view_mode, array $third_party_settings, EntityFieldManager $entityFieldManager, EntityTypeManagerInterface $entityTypeManager, RendererInterface $renderer, NameFormatterService $formatter, NameFormatParser $parser, NameGeneratorInterface $generator) {
    parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings);
    $this->entityFieldManager = $entityFieldManager;
    $this->entityTypeManager = $entityTypeManager;
    $this->renderer = $renderer;
    $this->formatter = $formatter;
    $this->parser = $parser;
    $this->generator = $generator;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($plugin_id, $plugin_definition, $configuration['field_definition'], $configuration['settings'], $configuration['label'], $configuration['view_mode'], $configuration['third_party_settings'], $container
      ->get('entity_field.manager'), $container
      ->get('entity_type.manager'), $container
      ->get('renderer'), $container
      ->get('name.formatter'), $container
      ->get('name.format_parser'), $container
      ->get('name.generator'));
  }

  /**
   * {@inheritdoc}
   */
  public static function defaultSettings() {
    $settings = parent::defaultSettings();
    $settings += [
      "format" => "default",
      "markup" => "none",
      "list_format" => "",
      "link_target" => "",
    ];
    $settings += self::getDefaultAdditionalPreferredSettings();
    return $settings;
  }

  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, FormStateInterface $form_state) {
    $elements = parent::settingsForm($form, $form_state);
    $elements['format'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Name format'),
      '#default_value' => $this
        ->getSetting('format'),
      '#options' => name_get_custom_format_options(),
      '#required' => TRUE,
    ];
    $elements['list_format'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('List format'),
      '#default_value' => $this
        ->getSetting('list_format'),
      '#empty_option' => $this
        ->t('-- individually --'),
      '#options' => name_get_custom_list_format_options(),
    ];
    $elements['markup'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Markup'),
      '#default_value' => $this
        ->getSetting('markup'),
      '#options' => $this->parser
        ->getMarkupOptions(),
      '#description' => $this
        ->t('This option wraps the individual components of the name in SPAN elements with corresponding classes to the component.'),
      '#required' => TRUE,
    ];
    if (!empty($this->fieldDefinition
      ->getTargetBundle())) {
      $elements['link_target'] = [
        '#type' => 'select',
        '#title' => $this
          ->t('Link Target'),
        '#default_value' => $this
          ->getSetting('link_target'),
        '#empty_option' => $this
          ->t('-- no link --'),
        '#options' => $this
          ->getLinkableTargets(),
      ];
      $elements += $this
        ->getNameAdditionalPreferredSettingsForm($form, $form_state);
    }
    return $elements;
  }

  /**
   * {@inheritdoc}
   */
  public function settingsSummary() {
    $settings = $this
      ->getSettings();
    $summary = [];

    // Name format.
    $machine_name = isset($settings['format']) ? $settings['format'] : 'default';
    $name_format = $this->entityTypeManager
      ->getStorage('name_format')
      ->load($machine_name);
    if ($name_format) {
      $summary[] = $this
        ->t('Format: @format (@machine_name)', [
        '@format' => $name_format
          ->label(),
        '@machine_name' => $name_format
          ->id(),
      ]);
    }
    else {
      $summary[] = $this
        ->t('Format: <strong>Missing format.</strong><br/>This field will be displayed using the Default format.');
    }

    // List format.
    if (!isset($settings['list_format']) || $settings['list_format'] == '') {
      $summary[] = $this
        ->t('List format: Individually');
    }
    else {
      $machine_name = isset($settings['list_format']) ? $settings['list_format'] : 'default';
      $name_format = $this->entityTypeManager
        ->getStorage('name_list_format')
        ->load($machine_name);
      if ($name_format) {
        $summary[] = $this
          ->t('List format: @format (@machine_name)', [
          '@format' => $name_format
            ->label(),
          '@machine_name' => $name_format
            ->id(),
        ]);
      }
      else {
        $summary[] = $this
          ->t('List format: <strong>Missing list format.</strong><br/>This field will be displayed using the Default list format.');
      }
    }

    // Additional options.
    $markup_options = $this->parser
      ->getMarkupOptions();
    $summary[] = $this
      ->t('Markup: @type', [
      '@type' => $markup_options[$this
        ->getSetting('markup')],
    ]);
    if (!empty($settings['link_target'])) {
      $targets = $this
        ->getLinkableTargets();
      $summary[] = $this
        ->t('Link: @target', [
        '@target' => empty($targets[$settings['link_target']]) ? $this
          ->t('-- invalid --') : $targets[$settings['link_target']],
      ]);
    }
    $this
      ->settingsNameAdditionalPreferredSummary($summary);

    // Provide an example of the selected format.
    if ($name_format) {
      $names = $this->generator
        ->loadSampleValues(1, $this->fieldDefinition);
      if ($name = reset($names)) {
        $formatted = $this->parser
          ->parse($name, $name_format
          ->get('pattern'));
        if (empty($formatted)) {
          $summary[] = $this
            ->t('Example: <em>&lt;&lt;empty&gt;&gt;</em>');
        }
        else {
          $summary[] = $this
            ->t('Example: @example', [
            '@example' => $formatted,
          ]);
        }
      }
    }
    return $summary;
  }

  /**
   * {@inheritdoc}
   */
  public function viewElements(FieldItemListInterface $items, $langcode) {
    $elements = [];
    if (!$items
      ->count()) {
      return $elements;
    }
    $settings = $this->settings;
    $format = isset($settings['format']) ? $settings['format'] : 'default';
    $is_multiple = $this->fieldDefinition
      ->getFieldStorageDefinition()
      ->isMultiple() && $items
      ->count() > 1;
    $list_format = $is_multiple && !empty($settings['list_format']) ? $settings['list_format'] : '';
    $extra = $this
      ->parseAdditionalComponents($items);
    $extra['url'] = empty($settings['link_target']) ? NULL : $this
      ->getLinkableTargetUrl($items);
    $item_array = [];
    foreach ($items as $item) {
      $components = $item
        ->toArray() + $extra;
      $item_array[] = $components;
    }
    $this->formatter
      ->setSetting('markup', $this
      ->getSetting('markup'));
    if ($list_format) {
      $elements[0]['#markup'] = $this->formatter
        ->formatList($item_array, $format, $list_format, $langcode);
    }
    else {
      foreach ($item_array as $delta => $item) {
        $elements[$delta]['#markup'] = $this->formatter
          ->format($item, $format, $langcode);
      }
    }
    return $elements;
  }

  /**
   * Determines with markup should be added to the results.
   *
   * @return bool
   *   Returns TRUE if markup should be applied.
   */
  protected function useMarkup() {
    return $this->settings['markup'];
  }

  /**
   * Find any linkable targets.
   *
   * @return array
   *   An array of possible targets.
   */
  protected function getLinkableTargets() {
    $targets = [
      '_self' => $this
        ->t('Entity URL'),
    ];
    $bundle = $this->fieldDefinition
      ->getTargetBundle();
    $entity_type_id = $this->fieldDefinition
      ->getTargetEntityTypeId();
    $fields = $this->entityFieldManager
      ->getFieldDefinitions($entity_type_id, $bundle);
    foreach ($fields as $field) {
      if (!$field
        ->getFieldStorageDefinition()
        ->isBaseField()) {
        switch ($field
          ->getType()) {
          case 'entity_reference':
          case 'link':
            $targets[$field
              ->getName()] = $field
              ->getLabel();
            break;
        }
      }
    }
    return $targets;
  }

  /**
   * Gets the URL object.
   *
   * @param \Drupal\Core\Field\FieldItemListInterface $items
   *   The name formatters FieldItemList.
   *
   * @return \Drupal\Core\Url
   *   Returns a Url object.
   */
  protected function getLinkableTargetUrl(FieldItemListInterface $items) {
    try {
      $parent = $items
        ->getEntity();
      if ($this->settings['link_target'] == '_self') {
        if (!$parent
          ->isNew() && $parent
          ->access('view')) {
          return $parent
            ->toUrl();
        }
      }
      elseif ($parent
        ->hasField($this->settings['link_target'])) {
        $target_items = $parent
          ->get($this->settings['link_target']);
        if (!$target_items
          ->isEmpty()) {
          $field = $target_items
            ->getFieldDefinition();
          switch ($field
            ->getType()) {
            case 'entity_reference':
              foreach ($target_items as $item) {
                if (!empty($item->entity) && !$item->entity
                  ->isNew() && $item->entity
                  ->access('view')) {
                  return $item->entity
                    ->toUrl();
                }
              }
              break;
            case 'link':
              foreach ($target_items as $item) {
                if ($url = $item
                  ->getUrl()) {
                  return $url;
                }
              }
              break;
          }
        }
      }
    } catch (UndefinedLinkTemplateException $e) {
    }
    return Url::fromRoute('<none>');
  }

  /**
   * Gets any additional linked components.
   *
   * @param \Drupal\Core\Field\FieldItemListInterface $items
   *   The name formatters FieldItemList.
   *
   * @return array
   *   An array of any additional components if set.
   */
  protected function parseAdditionalComponents(FieldItemListInterface $items) {
    $extra = [];
    foreach ([
      'preferred',
      'alternative',
    ] as $key) {
      $key_value = $this
        ->getSetting($key . '_field_reference');
      $sep_value = $this
        ->getSetting($key . '_field_reference_separator');
      if (!$key_value) {
        $key_value = $this->fieldDefinition
          ->getSetting($key . '_field_reference');
        $sep_value = $this->fieldDefinition
          ->getSetting($key . '_field_reference_separator');
      }
      if ($value = name_get_additional_component($this->entityTypeManager, $this->renderer, $items, $key_value, $sep_value)) {
        $extra[$key] = $value;
      }
    }
    return $extra;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
FormatterBase::$fieldDefinition protected property The field definition.
FormatterBase::$label protected property The label display setting.
FormatterBase::$settings protected property The formatter settings. Overrides PluginSettingsBase::$settings
FormatterBase::$viewMode protected property The view mode.
FormatterBase::getFieldSetting protected function Returns the value of a field setting.
FormatterBase::getFieldSettings protected function Returns the array of field settings.
FormatterBase::isApplicable public static function Returns if the formatter can be used for the provided field. Overrides FormatterInterface::isApplicable 14
FormatterBase::prepareView public function Allows formatters to load information for field values being displayed. Overrides FormatterInterface::prepareView 2
FormatterBase::view public function Builds a renderable array for a fully themed field. Overrides FormatterInterface::view 1
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
NameAdditionalPreferredTrait::getAdditionalSources protected function Helper function to find attached fields to use as alternative sources.
NameAdditionalPreferredTrait::getDefaultAdditionalPreferredSettings protected static function Gets the default settings for alternative and preferred fields.
NameAdditionalPreferredTrait::getEmptyOption protected function
NameAdditionalPreferredTrait::getNameAdditionalPreferredSettingsForm protected function Returns a form for the default settings defined above.
NameAdditionalPreferredTrait::getTraitUsageIsField protected function
NameAdditionalPreferredTrait::settingsNameAdditionalPreferredSummary protected function
NameFormatter::$entityFieldManager protected property The entity field manager.
NameFormatter::$entityTypeManager protected property The entity type manager.
NameFormatter::$formatter protected property The name formatter.
NameFormatter::$generator protected property The name generator.
NameFormatter::$parser protected property The name format parser.
NameFormatter::$renderer protected property The field renderer for any additional components.
NameFormatter::create public static function Creates an instance of the plugin. Overrides FormatterBase::create
NameFormatter::defaultSettings public static function Defines the default settings for this plugin. Overrides PluginSettingsBase::defaultSettings
NameFormatter::getLinkableTargets protected function Find any linkable targets.
NameFormatter::getLinkableTargetUrl protected function Gets the URL object.
NameFormatter::parseAdditionalComponents protected function Gets any additional linked components.
NameFormatter::settingsForm public function Returns a form to configure settings for the formatter. Overrides FormatterBase::settingsForm
NameFormatter::settingsSummary public function Returns a short summary for the current formatter settings. Overrides FormatterBase::settingsSummary
NameFormatter::useMarkup protected function Determines with markup should be added to the results.
NameFormatter::viewElements public function Builds a renderable array for a field value. Overrides FormatterInterface::viewElements
NameFormatter::__construct public function Constructs a NameFormatter instance. Overrides FormatterBase::__construct
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
PluginSettingsBase::$defaultSettingsMerged protected property Whether default settings have been merged into the current $settings.
PluginSettingsBase::$thirdPartySettings protected property The plugin settings injected by third party modules.
PluginSettingsBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides DependentPluginInterface::calculateDependencies 6
PluginSettingsBase::getSetting public function Returns the value of a setting, or its default value if absent. Overrides PluginSettingsInterface::getSetting
PluginSettingsBase::getSettings public function Returns the array of settings, including defaults for missing settings. Overrides PluginSettingsInterface::getSettings
PluginSettingsBase::getThirdPartyProviders public function Gets the list of third parties that store information. Overrides ThirdPartySettingsInterface::getThirdPartyProviders
PluginSettingsBase::getThirdPartySetting public function Gets the value of a third-party setting. Overrides ThirdPartySettingsInterface::getThirdPartySetting
PluginSettingsBase::getThirdPartySettings public function Gets all third-party settings of a given module. Overrides ThirdPartySettingsInterface::getThirdPartySettings
PluginSettingsBase::mergeDefaults protected function Merges default settings values into $settings.
PluginSettingsBase::onDependencyRemoval public function Informs the plugin that some configuration it depends on will be deleted. Overrides PluginSettingsInterface::onDependencyRemoval 3
PluginSettingsBase::setSetting public function Sets the value of a setting for the plugin. Overrides PluginSettingsInterface::setSetting
PluginSettingsBase::setSettings public function Sets the settings for the plugin. Overrides PluginSettingsInterface::setSettings
PluginSettingsBase::setThirdPartySetting public function Sets the value of a third-party setting. Overrides ThirdPartySettingsInterface::setThirdPartySetting
PluginSettingsBase::unsetThirdPartySetting public function Unsets a third-party setting. Overrides ThirdPartySettingsInterface::unsetThirdPartySetting
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.