UriLinkFormatter.php 812 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. <?php
  2. namespace Drupal\Core\Field\Plugin\Field\FieldFormatter;
  3. use Drupal\Core\Field\FormatterBase;
  4. use Drupal\Core\Field\FieldItemListInterface;
  5. use Drupal\Core\Url;
  6. /**
  7. * Plugin implementation of the 'uri_link' formatter.
  8. *
  9. * @FieldFormatter(
  10. * id = "uri_link",
  11. * label = @Translation("Link to URI"),
  12. * field_types = {
  13. * "uri",
  14. * }
  15. * )
  16. */
  17. class UriLinkFormatter extends FormatterBase {
  18. /**
  19. * {@inheritdoc}
  20. */
  21. public function viewElements(FieldItemListInterface $items, $langcode) {
  22. $elements = [];
  23. foreach ($items as $delta => $item) {
  24. if (!$item->isEmpty()) {
  25. $elements[$delta] = [
  26. '#type' => 'link',
  27. '#url' => Url::fromUri($item->value),
  28. '#title' => $item->value,
  29. ];
  30. }
  31. }
  32. return $elements;
  33. }
  34. }