You are here

public function TaxonomyTermReferenceCsv::viewElements in Taxonomy Formatter 8

Builds a renderable array for a field value.

Parameters

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

string $langcode: The language that should be used to render the field.

Return value

array A renderable array for $items, as an array of child elements keyed by consecutive numeric indexes starting from 0.

Overrides FormatterInterface::viewElements

File

src/Plugin/Field/FieldFormatter/TaxonomyTermReferenceCsv.php, line 136
Contains \Drupal\taxonomy_formatter\Plugin\Field\FieldFormatter\TaxonomyTermReferenceCsv.

Class

TaxonomyTermReferenceCsv
Plugin annotation @FieldFormatter( id = "taxonomy_term_reference_csv", label = @Translation("Delimited"), field_types = { "entity_reference" } )

Namespace

Drupal\taxonomy_formatter\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $element = array();
  $separator = SafeMarkup::checkPlain($this
    ->getSetting('separator_option'));
  if ($this
    ->getSetting('element_option') != '- None -') {
    $elementwrap[0] = '<' . $this
      ->getSetting('element_option') . ' class="' . SafeMarkup::checkPlain($this
      ->getSetting('element_class')) . '">';
    $elementwrap[1] = '</' . $this
      ->getSetting('element_option') . '>';
  }
  else {
    $elementwrap[0] = '';
    $elementwrap[1] = '';
  }
  if ($this
    ->getSetting('wrapper_option') != '- None -') {
    $wrapper[0] = '<' . $this
      ->getSetting('wrapper_option') . ' class="' . \Drupal\Component\Utility\SafeMarkup::checkPlain($this
      ->getSetting('wrapper_class')) . '">';
    $wrapper[1] = '</' . $this
      ->getSetting('wrapper_option') . '>';
  }
  else {
    $wrapper[0] = '';
    $wrapper[1] = '';
  }
  $formatted = '';
  foreach ($this
    ->getEntitiesToView($items, $langcode) as $delta => $entity) {
    if ($this
      ->getSetting('links_option')) {
      $formatted .= $elementwrap[0] . $entity
        ->toLink()
        ->toString() . $elementwrap[1] . $separator;
    }
    else {
      $formatted .= $elementwrap[0] . SafeMarkup::checkPlain($entity
        ->label()) . $elementwrap[1] . $separator;
    }
  }
  $length = strlen($separator);
  $formatted = substr($formatted, 0, -$length);
  $formatted = $wrapper[0] . $formatted . $wrapper[1];
  $element[0]['#markup'] = $formatted;
  return $element;
}