You are here

public function FlippingBookLinkFormatter::viewElements in Flipping Book 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/FlippingBookLinkFormatter.php, line 39

Class

FlippingBookLinkFormatter
Plugin implementation of the 'flipping_book_link_formatter' formatter.

Namespace

Drupal\flipping_book\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $element = array();
  $entity = $items
    ->getEntity();
  foreach ($items as $delta => $item) {
    $items[$delta]->title = $entity
      ->getName();
  }
  $settings = $this
    ->getSettings();
  foreach ($items as $delta => $item) {

    // By default use the full URL as the link text.
    $url = $this
      ->buildUrl($item);
    $link_title = $url
      ->toString();

    // If the title field value is available, use it for the link text.
    if (empty($settings['url_only']) && !empty($item->title)) {
      $link_title = \Drupal::token()
        ->replace($item->title, [
        $entity
          ->getEntityTypeId() => $entity,
      ], [
        'clear' => TRUE,
      ]);
    }

    // Trim the link text to the desired length.
    if (!empty($settings['trim_length'])) {
      $link_title = Unicode::truncate($link_title, $settings['trim_length'], FALSE, TRUE);
    }
    if (!empty($settings['url_only']) && !empty($settings['url_plain'])) {
      $element[$delta] = array(
        '#plain_text' => $link_title,
      );
      if (!empty($item->_attributes)) {
        $content = str_replace('internal:/', '', $item->uri);
        $item->_attributes += array(
          'content' => $content,
        );
      }
    }
    else {
      $element[$delta] = array(
        '#type' => 'link',
        '#title' => $link_title,
        '#options' => $url
          ->getOptions(),
      );
      $element[$delta]['#url'] = $url;
      if (!empty($item->_attributes)) {
        $element[$delta]['#options'] += array(
          'attributes' => array(),
        );
        $element[$delta]['#options']['attributes'] += $item->_attributes;

        // Unset field item attributes since they have been included in the
        // formatter output and should not be rendered in the field template.
        unset($item->_attributes);
      }
    }
  }
  return $element;
}