You are here

protected function FromFieldFormatter::getFormatter in Formatter Field 8

Creates an appropriate formatter for the field.

Parameters

\Drupal\Core\Field\FieldItemListInterface $items: The field values to be rendered.

Return value

\Drupal\Core\Field\FormatterInterface|null|void A formatter object or null when plugin is not found.

2 calls to FromFieldFormatter::getFormatter()
FromFieldFormatter::prepareView in src/Plugin/Field/FieldFormatter/FromFieldFormatter.php
Allows formatters to load information for field values being displayed.
FromFieldFormatter::viewElements in src/Plugin/Field/FieldFormatter/FromFieldFormatter.php
Builds a renderable array for a field value.

File

src/Plugin/Field/FieldFormatter/FromFieldFormatter.php, line 113

Class

FromFieldFormatter
Plugin implementation of the 'formatter_field' formatter.

Namespace

Drupal\formatter_field\Plugin\Field\FieldFormatter

Code

protected function getFormatter(FieldItemListInterface $items) {
  $definitions = $this->fieldManager
    ->getFieldDefinitions($this->fieldDefinition
    ->getTargetEntityTypeId(), $this->fieldDefinition
    ->getTargetBundle());
  $target_field_name = $this->fieldDefinition
    ->getName();
  $target_definition = $definitions[$target_field_name];
  $formatter_field = NULL;
  foreach ($definitions as $field_name => $definition) {
    if ($definition
      ->getType() == 'formatter_field_formatter' && $definition
      ->getSetting('field') == $target_field_name) {
      $formatter_field = $field_name;
    }
  }
  if (!$formatter_field) {
    $message = $this
      ->t('Could not find appropriate formatter field to render %field_label.', [
      '%field_label' => $target_definition
        ->getLabel(),
    ]);
    drupal_set_message($message, 'warning');
    return;
  }
  $type = NULL;
  $settings = [];
  $field_items = $items
    ->getEntity()
    ->get($formatter_field);
  if (isset($field_items[0])) {
    $formatter_data = $field_items[0]
      ->getValue();
    $type = empty($formatter_data['type']) ? '' : $formatter_data['type'];
    $settings = empty($formatter_data['settings']) ? [] : unserialize($formatter_data['settings']);
  }
  if (!$type) {
    return;
  }
  $options = [
    'field_definition' => $target_definition,
    'configuration' => [
      'type' => $type,
      'settings' => $settings,
      'label' => '',
      'weight' => 0,
    ],
    'view_mode' => '_custom',
  ];
  $formatter = $this->formatterManager
    ->getInstance($options);
  return $formatter;
}