You are here

public function SoundCloudLinkFormatter::viewElements in SoundCloud field 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/SoundCloudLinkFormatter.php, line 98

Class

SoundCloudLinkFormatter
Plugin implementation of the 'soundcloud_link' formatter.

Namespace

Drupal\soundcloudfield\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $elements = array();
  $settings = $this
    ->getSettings();
  foreach ($items as $delta => $item) {
    if (!$item
      ->isEmpty()) {
      $link_title = $item->url;

      // Trim the link text to the desired length.
      if (!empty($settings['trim_length'])) {
        $link_title = Unicode::truncate($link_title, $settings['trim_length'], FALSE, TRUE);
      }
      $elements[$delta] = array(
        '#type' => 'link',
        '#url' => Url::fromUri($item->url),
        '#title' => $link_title,
        '#options' => array(),
      );
      if (!empty($item->_attributes)) {
        $elements[$delta]['#options'] += array(
          'attributes' => array(),
        );
        $elements[$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 $elements;
}