LinkWidget.php 16.8 KB
Newer Older
1 2
<?php

3
namespace Drupal\link\Plugin\Field\FieldWidget;
4

5
use Drupal\Core\Entity\Element\EntityAutocomplete;
6
use Drupal\Core\Field\FieldItemListInterface;
7
use Drupal\Core\Field\WidgetBase;
8
use Drupal\Core\Form\FormStateInterface;
9
use Drupal\link\LinkItemInterface;
10 11
use Symfony\Component\Validator\ConstraintViolation;
use Symfony\Component\Validator\ConstraintViolationListInterface;
12 13 14 15

/**
 * Plugin implementation of the 'link' widget.
 *
16
 * @FieldWidget(
17 18 19 20 21 22 23 24 25
 *   id = "link_default",
 *   label = @Translation("Link"),
 *   field_types = {
 *     "link"
 *   }
 * )
 */
class LinkWidget extends WidgetBase {

26 27 28 29
  /**
   * {@inheritdoc}
   */
  public static function defaultSettings() {
30
    return [
31 32
      'placeholder_url' => '',
      'placeholder_title' => '',
33
    ] + parent::defaultSettings();
34 35
  }

36
  /**
37
   * Gets the URI without the 'internal:' or 'entity:' scheme.
38 39 40
   *
   * The following two forms of URIs are transformed:
   * - 'entity:' URIs: to entity autocomplete ("label (entity id)") strings;
41
   * - 'internal:' URIs: the scheme is stripped.
42 43
   *
   * This method is the inverse of ::getUserEnteredStringAsUri().
44 45 46 47 48
   *
   * @param string $uri
   *   The URI to get the displayable string for.
   *
   * @return string
49 50
   *
   * @see static::getUserEnteredStringAsUri()
51
   */
52
  protected static function getUriAsDisplayableString($uri) {
53
    $scheme = parse_url($uri, PHP_URL_SCHEME);
54 55 56 57

    // By default, the displayable string is the URI.
    $displayable_string = $uri;

58
    // A different displayable string may be chosen in case of the 'internal:'
59
    // or 'entity:' built-in schemes.
60
    if ($scheme === 'internal') {
61
      $uri_reference = explode(':', $uri, 2)[1];
62 63 64

      // @todo '<front>' is valid input for BC reasons, may be removed by
      //   https://www.drupal.org/node/2421941
65 66 67 68
      $path = parse_url($uri, PHP_URL_PATH);
      if ($path === '/') {
        $uri_reference = '<front>' . substr($uri_reference, 1);
      }
69 70

      $displayable_string = $uri_reference;
71
    }
72 73
    elseif ($scheme === 'entity') {
      list($entity_type, $entity_id) = explode('/', substr($uri, 7), 2);
74
      // Show the 'entity:' URI as the entity autocomplete would.
75 76 77
      // @todo Support entity types other than 'node'. Will be fixed in
      //    https://www.drupal.org/node/2423093.
      if ($entity_type == 'node' && $entity = \Drupal::entityTypeManager()->getStorage($entity_type)->load($entity_id)) {
78
        $displayable_string = EntityAutocomplete::getEntityLabels([$entity]);
79
      }
80
    }
81 82

    return $displayable_string;
83 84
  }

85 86 87
  /**
   * Gets the user-entered string as a URI.
   *
88 89
   * The following two forms of input are mapped to URIs:
   * - entity autocomplete ("label (entity id)") strings: to 'entity:' URIs;
90
   * - strings without a detectable scheme: to 'internal:' URIs.
91 92
   *
   * This method is the inverse of ::getUriAsDisplayableString().
93
   *
94
   * @param string $string
95 96 97
   *   The user-entered string.
   *
   * @return string
98 99 100
   *   The URI, if a non-empty $uri was passed.
   *
   * @see static::getUriAsDisplayableString()
101
   */
102
  protected static function getUserEnteredStringAsUri($string) {
103 104 105 106 107 108 109 110 111 112
    // By default, assume the entered string is an URI.
    $uri = $string;

    // Detect entity autocomplete string, map to 'entity:' URI.
    $entity_id = EntityAutocomplete::extractEntityIdFromAutocompleteInput($string);
    if ($entity_id !== NULL) {
      // @todo Support entity types other than 'node'. Will be fixed in
      //    https://www.drupal.org/node/2423093.
      $uri = 'entity:node/' . $entity_id;
    }
113
    // Detect a schemeless string, map to 'internal:' URI.
114 115 116 117 118 119 120
    elseif (!empty($string) && parse_url($string, PHP_URL_SCHEME) === NULL) {
      // @todo '<front>' is valid input for BC reasons, may be removed by
      //   https://www.drupal.org/node/2421941
      // - '<front>' -> '/'
      // - '<front>#foo' -> '/#foo'
      if (strpos($string, '<front>') === 0) {
        $string = '/' . substr($string, strlen('<front>'));
121
      }
122
      $uri = 'internal:' . $string;
123
    }
124 125

    return $uri;
126 127 128
  }

  /**
129 130
   * Form element validation handler for the 'uri' element.
   *
131 132 133 134
   * Disallows saving inaccessible or untrusted URLs.
   */
  public static function validateUriElement($element, FormStateInterface $form_state, $form) {
    $uri = static::getUserEnteredStringAsUri($element['#value']);
135 136
    $form_state->setValueForElement($element, $uri);

137
    // If getUserEnteredStringAsUri() mapped the entered value to a 'internal:'
138
    // URI , ensure the raw value begins with '/', '?' or '#'.
139 140
    // @todo '<front>' is valid input for BC reasons, may be removed by
    //   https://www.drupal.org/node/2421941
141
    if (parse_url($uri, PHP_URL_SCHEME) === 'internal' && !in_array($element['#value'][0], ['/', '?', '#'], TRUE) && substr($element['#value'], 0, 7) !== '<front>') {
142
      $form_state->setError($element, t('Manually entered paths should start with /, ? or #.'));
143
      return;
144
    }
145 146
  }

147 148 149 150 151 152 153
  /**
   * Form element validation handler for the 'title' element.
   *
   * Conditionally requires the link title if a URL value was filled in.
   */
  public static function validateTitleElement(&$element, FormStateInterface $form_state, $form) {
    if ($element['uri']['#value'] !== '' && $element['title']['#value'] === '') {
154 155
      // We expect the field name placeholder value to be wrapped in t() here,
      // so it won't be escaped again as it's already marked safe.
156
      $form_state->setError($element['title'], t('@title field is required if there is @uri input.', ['@title' => $element['title']['#title'], '@uri' => $element['uri']['#title']]));
157 158 159
    }
  }

160 161 162 163 164 165 166 167 168 169 170
  /**
   * Form element validation handler for the 'title' element.
   *
   * Requires the URL value if a link title was filled in.
   */
  public static function validateTitleNoLink(&$element, FormStateInterface $form_state, $form) {
    if ($element['uri']['#value'] === '' && $element['title']['#value'] !== '') {
      $form_state->setError($element['uri'], t('The @uri field is required when the @title field is specified.', ['@title' => $element['title']['#title'], '@uri' => $element['uri']['#title']]));
    }
  }

171 172 173
  /**
   * {@inheritdoc}
   */
174
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
175 176
    /** @var \Drupal\link\LinkItemInterface $item */
    $item = $items[$delta];
177

178
    $element['uri'] = [
179
      '#type' => 'url',
180
      '#title' => $this->t('URL'),
181
      '#placeholder' => $this->getSetting('placeholder_url'),
182 183 184
      // The current field value could have been entered by a different user.
      // However, if it is inaccessible to the current user, do not display it
      // to them.
185
      '#default_value' => (!$item->isEmpty() && (\Drupal::currentUser()->hasPermission('link to any page') || $item->getUrl()->access())) ? static::getUriAsDisplayableString($item->uri) : NULL,
186
      '#element_validate' => [[get_called_class(), 'validateUriElement']],
187 188
      '#maxlength' => 2048,
      '#required' => $element['#required'],
189
      '#link_type' => $this->getFieldSetting('link_type'),
190
    ];
191 192 193 194

    // If the field is configured to support internal links, it cannot use the
    // 'url' form element and we have to do the validation ourselves.
    if ($this->supportsInternalLinks()) {
195 196 197 198 199 200
      $element['uri']['#type'] = 'entity_autocomplete';
      // @todo The user should be able to select an entity type. Will be fixed
      //    in https://www.drupal.org/node/2423093.
      $element['uri']['#target_type'] = 'node';
      // Disable autocompletion when the first character is '/', '#' or '?'.
      $element['uri']['#attributes']['data-autocomplete-first-character-blacklist'] = '/#?';
201 202 203 204

      // The link widget is doing its own processing in
      // static::getUriAsDisplayableString().
      $element['uri']['#process_default_value'] = FALSE;
205 206 207
    }

    // If the field is configured to allow only internal links, add a useful
208
    // element prefix and description.
209
    if (!$this->supportsExternalLinks()) {
210 211
      $element['uri']['#field_prefix'] = rtrim(\Drupal::url('<front>', [], ['absolute' => TRUE]), '/');
      $element['uri']['#description'] = $this->t('This must be an internal path such as %add-node. You can also start typing the title of a piece of content to select it. Enter %front to link to the front page.', ['%add-node' => '/node/add', '%front' => '<front>']);
212 213 214 215
    }
    // If the field is configured to allow both internal and external links,
    // show a useful description.
    elseif ($this->supportsExternalLinks() && $this->supportsInternalLinks()) {
216
      $element['uri']['#description'] = $this->t('Start typing the title of a piece of content to select it. You can also enter an internal path such as %add-node or an external URL such as %url. Enter %front to link to the front page.', ['%front' => '<front>', '%add-node' => '/node/add', '%url' => 'http://example.com']);
217
    }
218 219 220
    // If the field is configured to allow only external links, show a useful
    // description.
    elseif ($this->supportsExternalLinks() && !$this->supportsInternalLinks()) {
221
      $element['uri']['#description'] = $this->t('This must be an external URL such as %url.', ['%url' => 'http://example.com']);
222
    }
223

224
    $element['title'] = [
225
      '#type' => 'textfield',
226
      '#title' => $this->t('Link text'),
227
      '#placeholder' => $this->getSetting('placeholder_title'),
228
      '#default_value' => isset($items[$delta]->title) ? $items[$delta]->title : NULL,
229
      '#maxlength' => 255,
230
      '#access' => $this->getFieldSetting('title') != DRUPAL_DISABLED,
231
      '#required' => $this->getFieldSetting('title') === DRUPAL_REQUIRED && $element['#required'],
232
    ];
233 234 235
    // Post-process the title field to make it conditionally required if URL is
    // non-empty. Omit the validation on the field edit form, since the field
    // settings cannot be saved otherwise.
236 237 238
    //
    // Validate that title field is filled out (regardless of uri) when it is a
    // required field.
239
    if (!$this->isDefaultValueWidget($form_state) && $this->getFieldSetting('title') === DRUPAL_REQUIRED) {
240
      $element['#element_validate'][] = [get_called_class(), 'validateTitleElement'];
241
      $element['#element_validate'][] = [get_called_class(), 'validateTitleNoLink'];
242 243 244

      if (!$element['title']['#required']) {
        // Make title required on the front-end when URI filled-in.
245
        $field_name = $this->fieldDefinition->getName();
246 247 248 249 250 251 252 253 254 255 256 257

        $parents = $element['#field_parents'];
        $parents[] = $field_name;
        $selector = $root = array_shift($parents);
        if ($parents) {
          $selector = $root . '[' . implode('][', $parents) . ']';
        }

        $element['title']['#states']['required'] = [
          ':input[name="' . $selector . '[' . $delta . '][uri]"]' => ['filled' => TRUE]
        ];
      }
258 259
    }

260 261 262 263 264 265
    // Ensure that a URI is always entered when an optional title field is
    // submitted.
    if (!$this->isDefaultValueWidget($form_state) && $this->getFieldSetting('title') == DRUPAL_OPTIONAL) {
      $element['#element_validate'][] = [get_called_class(), 'validateTitleNoLink'];
    }

266 267
    // Exposing the attributes array in the widget is left for alternate and more
    // advanced field widgets.
268
    $element['attributes'] = [
269 270
      '#type' => 'value',
      '#tree' => TRUE,
271 272 273
      '#value' => !empty($items[$delta]->options['attributes']) ? $items[$delta]->options['attributes'] : [],
      '#attributes' => ['class' => ['link-field-widget-attributes']],
    ];
274

275
    // If cardinality is 1, ensure a proper label is output for the field.
276
    if ($this->fieldDefinition->getFieldStorageDefinition()->getCardinality() == 1) {
277 278 279 280
      // If the link title is disabled, use the field definition label as the
      // title of the 'uri' element.
      if ($this->getFieldSetting('title') == DRUPAL_DISABLED) {
        $element['uri']['#title'] = $element['#title'];
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
        // By default the field description is added to the title field. Since
        // the title field is disabled, we add the description, if given, to the
        // uri element instead.
        if (!empty($element['#description'])) {
          if (empty($element['uri']['#description'])) {
            $element['uri']['#description'] = $element['#description'];
          }
          else {
            // If we have the description of the type of field together with
            // the user provided description, we want to make a distinction
            // between "core help text" and "user entered help text". To make
            // this distinction more clear, we put them in an unordered list.
            $element['uri']['#description'] = [
              '#theme' => 'item_list',
              '#items' => [
                // Assume the user-specified description has the most relevance,
                // so place it first.
                $element['#description'],
                $element['uri']['#description'],
              ],
            ];
          }
        }
304 305 306
      }
      // Otherwise wrap everything in a details element.
      else {
307
        $element += [
308
          '#type' => 'fieldset',
309
        ];
310
      }
311 312 313 314 315
    }

    return $element;
  }

316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
  /**
   * Indicates enabled support for link to routes.
   *
   * @return bool
   *   Returns TRUE if the LinkItem field is configured to support links to
   *   routes, otherwise FALSE.
   */
  protected function supportsInternalLinks() {
    $link_type = $this->getFieldSetting('link_type');
    return (bool) ($link_type & LinkItemInterface::LINK_INTERNAL);
  }

  /**
   * Indicates enabled support for link to external URLs.
   *
   * @return bool
   *   Returns TRUE if the LinkItem field is configured to support links to
   *   external URLs, otherwise FALSE.
   */
  protected function supportsExternalLinks() {
    $link_type = $this->getFieldSetting('link_type');
    return (bool) ($link_type & LinkItemInterface::LINK_EXTERNAL);
  }

340 341 342
  /**
   * {@inheritdoc}
   */
343
  public function settingsForm(array $form, FormStateInterface $form_state) {
344 345
    $elements = parent::settingsForm($form, $form_state);

346
    $elements['placeholder_url'] = [
347
      '#type' => 'textfield',
348
      '#title' => $this->t('Placeholder for URL'),
349
      '#default_value' => $this->getSetting('placeholder_url'),
350
      '#description' => $this->t('Text that will be shown inside the field until a value is entered. This hint is usually a sample value or a brief description of the expected format.'),
351 352
    ];
    $elements['placeholder_title'] = [
353
      '#type' => 'textfield',
354
      '#title' => $this->t('Placeholder for link text'),
355
      '#default_value' => $this->getSetting('placeholder_title'),
356
      '#description' => $this->t('Text that will be shown inside the field until a value is entered. This hint is usually a sample value or a brief description of the expected format.'),
357 358 359 360 361 362
      '#states' => [
        'invisible' => [
          ':input[name="instance[settings][title]"]' => ['value' => DRUPAL_DISABLED],
        ],
      ],
    ];
363 364 365 366

    return $elements;
  }

367 368 369 370
  /**
   * {@inheritdoc}
   */
  public function settingsSummary() {
371
    $summary = [];
372 373 374 375

    $placeholder_title = $this->getSetting('placeholder_title');
    $placeholder_url = $this->getSetting('placeholder_url');
    if (empty($placeholder_title) && empty($placeholder_url)) {
376
      $summary[] = $this->t('No placeholders');
377 378 379
    }
    else {
      if (!empty($placeholder_title)) {
380
        $summary[] = $this->t('Title placeholder: @placeholder_title', ['@placeholder_title' => $placeholder_title]);
381 382
      }
      if (!empty($placeholder_url)) {
383
        $summary[] = $this->t('URL placeholder: @placeholder_url', ['@placeholder_url' => $placeholder_url]);
384 385 386 387 388 389
      }
    }

    return $summary;
  }

390 391 392
  /**
   * {@inheritdoc}
   */
393
  public function massageFormValues(array $values, array $form, FormStateInterface $form_state) {
394
    foreach ($values as &$value) {
395 396
      $value['uri'] = static::getUserEnteredStringAsUri($value['uri']);
      $value += ['options' => []];
397 398 399 400
    }
    return $values;
  }

401 402 403 404

  /**
   * {@inheritdoc}
   *
405
   * Override the '%uri' message parameter, to ensure that 'internal:' URIs
406 407 408 409 410
   * show a validation error message that doesn't mention that scheme.
   */
  public function flagErrors(FieldItemListInterface $items, ConstraintViolationListInterface $violations, array $form, FormStateInterface $form_state) {
    /** @var \Symfony\Component\Validator\ConstraintViolationInterface $violation */
    foreach ($violations as $offset => $violation) {
411
      $parameters = $violation->getParameters();
412 413
      if (isset($parameters['@uri'])) {
        $parameters['@uri'] = static::getUriAsDisplayableString($parameters['@uri']);
414 415 416 417 418 419 420
        $violations->set($offset, new ConstraintViolation(
          $this->t($violation->getMessageTemplate(), $parameters),
          $violation->getMessageTemplate(),
          $parameters,
          $violation->getRoot(),
          $violation->getPropertyPath(),
          $violation->getInvalidValue(),
421
          $violation->getPlural(),
422 423 424 425 426 427 428
          $violation->getCode()
        ));
      }
    }
    parent::flagErrors($items, $violations, $form, $form_state);
  }

429
}