You are here

protected function Link::getUrlFromField in Field Group Link 8

Same name and namespace in other branches
  1. 8.3 src/Plugin/field_group/FieldGroupFormatter/Link.php \Drupal\field_group_link\Plugin\field_group\FieldGroupFormatter\Link::getUrlFromField()

Retrieve the url object from a field.

Parameters

\Drupal\Core\Entity\EntityInterface $entity: The object of the current entity.

Return value

\Drupal\Core\Url|null Either a valid Url object, or NULL.

1 call to Link::getUrlFromField()
Link::preRender in src/Plugin/field_group/FieldGroupFormatter/Link.php

File

src/Plugin/field_group/FieldGroupFormatter/Link.php, line 228

Class

Link
Plugin implementation of the 'link' formatter.

Namespace

Drupal\field_group_link\Plugin\field_group\FieldGroupFormatter

Code

protected function getUrlFromField(EntityInterface $entity) {
  $url = NULL;
  $field_name = $this
    ->getSetting('target');

  // Make sure the field (still) exists. Also filters out _none.
  if ($field_definition = $entity
    ->getFieldDefinition($field_name)) {
    $field_value = $entity
      ->get($field_name)
      ->getValue();
    if (!empty($field_value[0])) {
      switch ($field_definition
        ->getType()) {
        case 'link':
          $url = Url::fromUri($field_value[0]['uri']);
          break;
        case 'image':
        case 'file':
          $file = File::load($field_value[0]['target_id']);

          // @todo: Change to $file->toUrl() once
          // https://www.drupal.org/node/2402533 is resolved.
          $url = Url::fromUri(file_create_url($file
            ->getFileUri()));
          break;
        case 'entity_reference':
          $target_entity = \Drupal::entityTypeManager()
            ->getStorage($field_definition
            ->getSetting('target_type'))
            ->load($field_value[0]['target_id']);
          $url = $target_entity
            ->toUrl();
          break;
      }
    }
  }
  return $url;
}