LinkFormatter.php 6.13 KB
Newer Older
1 2 3 4 5 6 7
<?php

/**
 * @file
 * Contains \Drupal\link\Plugin\field\formatter\LinkFormatter.
 */

8
namespace Drupal\link\Plugin\Field\FieldFormatter;
9

10
use Drupal\Component\Utility\String;
11
use Drupal\Component\Utility\Unicode;
12
use Drupal\Core\Field\FieldItemListInterface;
13
use Drupal\Core\Field\FormatterBase;
14
use Drupal\Core\Form\FormStateInterface;
15 16
use Drupal\Core\Url;
use Drupal\link\LinkItemInterface;
17
use Symfony\Component\HttpFoundation\Request;
18 19 20 21

/**
 * Plugin implementation of the 'link' formatter.
 *
22
 * @FieldFormatter(
23 24 25 26 27 28 29 30 31
 *   id = "link",
 *   label = @Translation("Link"),
 *   field_types = {
 *     "link"
 *   }
 * )
 */
class LinkFormatter extends FormatterBase {

32 33 34 35 36 37 38 39 40 41 42 43 44
  /**
   * {@inheritdoc}
   */
  public static function defaultSettings() {
    return array(
      'trim_length' => '80',
      'url_only' => '',
      'url_plain' => '',
      'rel' => '',
      'target' => '',
    ) + parent::defaultSettings();
  }

45 46 47
  /**
   * {@inheritdoc}
   */
48
  public function settingsForm(array $form, FormStateInterface $form_state) {
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
    $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');
    }

121
    return $summary;
122 123 124 125 126
  }

  /**
   * {@inheritdoc}
   */
127
  public function viewElements(FieldItemListInterface $items) {
128
    $element = array();
129
    $entity = $items->getEntity();
130 131 132
    $settings = $this->getSettings();

    foreach ($items as $delta => $item) {
133
      // By default use the full URL as the link text.
134 135
      $url = $this->buildUrl($item);
      $link_title = $url->toString();
136

137
      // If the title field value is available, use it for the link text.
138
      if (empty($settings['url_only']) && !empty($item->title)) {
139
        // Unsanitized token replacement here because $options['html'] is FALSE
140
        // by default in _l().
141
        $link_title = \Drupal::token()->replace($item->title, array($entity->getEntityTypeId() => $entity), array('sanitize' => FALSE, 'clear' => TRUE));
142 143
      }

144
      // Trim the link text to the desired length.
145
      if (!empty($settings['trim_length'])) {
146
        $link_title = Unicode::truncate($link_title, $settings['trim_length'], FALSE, TRUE);
147 148 149 150
      }

      if (!empty($settings['url_only']) && !empty($settings['url_plain'])) {
        $element[$delta] = array(
151
          '#markup' => String::checkPlain($link_title),
152
        );
153 154 155 156 157 158 159

        if (!empty($item->_attributes)) {
          // Piggyback on the metadata attributes, which will be placed in the
          // field template wrapper, and set the URL value in a content
          // attribute.
          $item->_attributes += array('content' => $item->url);
        }
160 161 162 163 164
      }
      else {
        $element[$delta] = array(
          '#type' => 'link',
          '#title' => $link_title,
165
          '#options' => $url->getOptions(),
166
        );
167
        $element[$delta]['#url'] = $url;
168 169 170 171 172 173 174 175

        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);
        }
176 177 178 179 180
      }
    }

    return $element;
  }
181 182

  /**
183
   * Builds the \Drupal\Core\Url object for a link field item.
184
   *
185
   * @param \Drupal\link\LinkItemInterface $item
186 187
   *   The link field item being rendered.
   *
188 189
   * @return \Drupal\Core\Url
   *   An Url object.
190
   */
191
  protected function buildUrl(LinkItemInterface $item) {
192
    $settings = $this->getSettings();
193
    $options = $item->options;
194 195 196

    // Add optional 'rel' attribute to link options.
    if (!empty($settings['rel'])) {
197
      $options['attributes']['rel'] = $settings['rel'];
198 199 200
    }
    // Add optional 'target' attribute to link options.
    if (!empty($settings['target'])) {
201 202 203 204
      $options['attributes']['target'] = $settings['target'];
    }

    if ($item->isExternal()) {
205
      $url = Url::fromUri($item->url, $options);
206 207
    }
    else {
208
      $url = Url::fromRoute($item->route_name, (array) $item->route_parameters, (array) $options);
209 210
    }

211
    return $url;
212 213
  }

214
}