class LinkFormatter

Same name in this branch

Plugin implementation of the 'link' formatter.

Plugin annotation


@FieldFormatter(
  id = "link",
  module = "link",
  label = @Translation("Link"),
  field_types = {
    "link"
  },
  settings = {
    "trim_length" = "80",
    "url_only" = "",
    "url_plain" = "",
    "rel" = "",
    "target" = ""
  }
)

Hierarchy

Expanded class hierarchy of LinkFormatter

File

drupal/core/modules/link/lib/Drupal/link/Plugin/field/formatter/LinkFormatter.php, line 34
Contains \Drupal\link\Plugin\field\formatter\LinkFormatter.

Namespace

Drupal\link\Plugin\field\formatter
View source
class LinkFormatter extends FormatterBase {

  /**
   * {@inheritdoc}
   */
  public function settingsForm(array $form, array &$form_state) {
    $elements = parent::settingsForm($form, $form_state);
    $elements['trim_length'] = array(
      '#type' => 'number',
      '#title' => t('Trim link text length'),
      '#field_suffix' => t('characters'),
      '#default_value' => $this
        ->getSetting('trim_length'),
      '#min' => 1,
      '#description' => t('Leave blank to allow unlimited link text lengths.'),
    );
    $elements['url_only'] = array(
      '#type' => 'checkbox',
      '#title' => t('URL only'),
      '#default_value' => $this
        ->getSetting('url_only'),
      '#access' => $this
        ->getPluginId() == 'link',
    );
    $elements['url_plain'] = array(
      '#type' => 'checkbox',
      '#title' => t('Show URL as plain text'),
      '#default_value' => $this
        ->getSetting('url_plain'),
      '#access' => $this
        ->getPluginId() == 'link',
      '#states' => array(
        'visible' => array(
          ':input[name*="url_only"]' => array(
            'checked' => TRUE,
          ),
        ),
      ),
    );
    $elements['rel'] = array(
      '#type' => 'checkbox',
      '#title' => t('Add rel="nofollow" to links'),
      '#return_value' => 'nofollow',
      '#default_value' => $this
        ->getSetting('rel'),
    );
    $elements['target'] = array(
      '#type' => 'checkbox',
      '#title' => t('Open link in new window'),
      '#return_value' => '_blank',
      '#default_value' => $this
        ->getSetting('target'),
    );
    return $elements;
  }

  /**
   * {@inheritdoc}
   */
  public function settingsSummary() {
    $summary = array();
    $settings = $this
      ->getSettings();
    if (!empty($settings['trim_length'])) {
      $summary[] = t('Link text trimmed to @limit characters', array(
        '@limit' => $settings['trim_length'],
      ));
    }
    else {
      $summary[] = t('Link text not trimmed');
    }
    if ($this
      ->getPluginId() == 'link' && !empty($settings['url_only'])) {
      if (!empty($settings['url_plain'])) {
        $summary[] = t('Show URL only as plain-text');
      }
      else {
        $summary[] = t('Show URL only');
      }
    }
    if (!empty($settings['rel'])) {
      $summary[] = t('Add rel="@rel"', array(
        '@rel' => $settings['rel'],
      ));
    }
    if (!empty($settings['target'])) {
      $summary[] = t('Open link in new window');
    }
    return $summary;
  }

  /**
   * {@inheritdoc}
   */
  public function prepareView(array $entities, $langcode, array &$items) {
    $settings = $this
      ->getSettings();
    foreach ($entities as $id => $entity) {
      foreach ($items[$id] as $delta => &$item) {

        // Split out the link into the parts required for url(): path and options.
        $parsed = drupal_parse_url($item['url']);
        $item['path'] = $parsed['path'];
        $item['options'] = array(
          'query' => $parsed['query'],
          'fragment' => $parsed['fragment'],
          'attributes' => &$item['attributes'],
        );

        // Add optional 'rel' attribute to link options.
        if (!empty($settings['rel'])) {
          $item['options']['attributes']['rel'] = $settings['rel'];
        }

        // Add optional 'target' attribute to link options.
        if (!empty($settings['target'])) {
          $item['options']['attributes']['target'] = $settings['target'];
        }
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function viewElements(EntityInterface $entity, $langcode, array $items) {
    $element = array();
    $settings = $this
      ->getSettings();
    foreach ($items as $delta => $item) {

      // By default use the full URL as the link text.
      $link_title = $item['url'];

      // If the title field value is available, use it for the link text.
      if (empty($settings['url_only']) && !empty($item['title'])) {

        // Unsanitizied token replacement here because $options['html'] is FALSE
        // by default in theme_link().
        $link_title = \Drupal::token()
          ->replace($item['title'], array(
          $entity
            ->entityType() => $entity,
        ), array(
          'sanitize' => FALSE,
          'clear' => TRUE,
        ));
      }

      // Trim the link text to the desired length.
      if (!empty($settings['trim_length'])) {
        $link_title = truncate_utf8($link_title, $settings['trim_length'], FALSE, TRUE);
      }
      if (!empty($settings['url_only']) && !empty($settings['url_plain'])) {
        $element[$delta] = array(
          '#type' => 'markup',
          '#markup' => check_plain($link_title),
        );
      }
      else {
        $element[$delta] = array(
          '#type' => 'link',
          '#title' => $link_title,
          '#href' => $item['path'],
          '#options' => $item['options'],
        );
      }
    }
    return $element;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
FormatterBase::$field protected property The field definition.
FormatterBase::$instance protected property The field instance definition.
FormatterBase::$label protected property The label display setting.
FormatterBase::$settings protected property The formatter settings. Overrides PluginSettingsBase::$settings
FormatterBase::$viewMode protected property The view mode.
FormatterBase::view public function Builds a renderable array for one field on one entity instance. Overrides FormatterInterface::view
FormatterBase::__construct public function Constructs a FormatterBase object. Overrides PluginBase::__construct
LinkFormatter::prepareView public function Allows formatters to load information for field values being displayed. Overrides FormatterBase::prepareView
LinkFormatter::settingsForm public function Returns a form to configure settings for the formatter. Overrides FormatterBase::settingsForm
LinkFormatter::settingsSummary public function Returns a short summary for the current formatter settings. Overrides FormatterBase::settingsSummary
LinkFormatter::viewElements public function Builds a renderable array for a field value. Overrides FormatterInterface::viewElements 1
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition.
PluginBase::$pluginId protected property The plugin_id.
PluginBase::getPluginDefinition public function Returns the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition
PluginBase::getPluginId public function Returns the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginSettingsBase::$defaultSettingsMerged protected property Whether default settings have been merged into the current $settings.
PluginSettingsBase::getDefaultSettings public function Implements Drupal\field\Plugin\PluginSettingsInterface::getDefaultSettings(). Overrides PluginSettingsInterface::getDefaultSettings
PluginSettingsBase::getSetting public function Implements Drupal\field\Plugin\PluginSettingsInterface::getSetting(). Overrides PluginSettingsInterface::getSetting
PluginSettingsBase::getSettings public function Implements Drupal\field\Plugin\PluginSettingsInterface::getSettings(). Overrides PluginSettingsInterface::getSettings
PluginSettingsBase::mergeDefaults protected function Merges default settings values into $settings.
PluginSettingsBase::setSetting public function Implements Drupal\field\Plugin\PluginSettingsInterface::setSetting(). Overrides PluginSettingsInterface::setSetting
PluginSettingsBase::setSettings public function Implements Drupal\field\Plugin\PluginSettingsInterface::setSettings(). Overrides PluginSettingsInterface::setSettings