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

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

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

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

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

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

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

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

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

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

    return $displayable_string;
87
88
  }

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

    // 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
114
      //   https://www.drupal.org/node/2423093.
115
116
      $uri = 'entity:node/' . $entity_id;
    }
117
    // Support linking to nothing.
118
    elseif (in_array($string, ['<nolink>', '<none>', '<button>'], TRUE)) {
119
120
      $uri = 'route:' . $string;
    }
121
    // Detect a schemeless string, map to 'internal:' URI.
122
123
124
125
126
127
128
    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>'));
129
      }
130
      $uri = 'internal:' . $string;
131
    }
132
133

    return $uri;
134
135
136
  }

  /**
137
138
   * Form element validation handler for the 'uri' element.
   *
139
140
141
142
   * Disallows saving inaccessible or untrusted URLs.
   */
  public static function validateUriElement($element, FormStateInterface $form_state, $form) {
    $uri = static::getUserEnteredStringAsUri($element['#value']);
143
144
    $form_state->setValueForElement($element, $uri);

145
    // If getUserEnteredStringAsUri() mapped the entered value to an 'internal:'
146
    // URI , ensure the raw value begins with '/', '?' or '#'.
147
148
    // @todo '<front>' is valid input for BC reasons, may be removed by
    //   https://www.drupal.org/node/2421941
149
    if (parse_url($uri, PHP_URL_SCHEME) === 'internal' && !in_array($element['#value'][0], ['/', '?', '#'], TRUE) && substr($element['#value'], 0, 7) !== '<front>') {
150
      $form_state->setError($element, t('Manually entered paths should start with one of the following characters: / ? #'));
151
      return;
152
    }
153
154
  }

155
156
157
158
159
160
161
  /**
   * 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'] === '') {
162
163
      // 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.
164
      $form_state->setError($element['title'], t('@title field is required if there is @uri input.', ['@title' => $element['title']['#title'], '@uri' => $element['uri']['#title']]));
165
166
167
    }
  }

168
169
170
171
172
173
174
175
176
177
178
  /**
   * 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']]));
    }
  }

179
180
181
  /**
   * {@inheritdoc}
   */
182
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
183
184
    /** @var \Drupal\link\LinkItemInterface $item */
    $item = $items[$delta];
185

186
    $element['uri'] = [
187
      '#type' => 'url',
188
      '#title' => $this->t('URL'),
189
      '#placeholder' => $this->getSetting('placeholder_url'),
190
191
192
      // 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.
193
      '#default_value' => (!$item->isEmpty() && (\Drupal::currentUser()->hasPermission('link to any page') || $item->getUrl()->access())) ? static::getUriAsDisplayableString($item->uri) : NULL,
194
      '#element_validate' => [[static::class, 'validateUriElement']],
195
196
      '#maxlength' => 2048,
      '#required' => $element['#required'],
197
      '#link_type' => $this->getFieldSetting('link_type'),
198
    ];
199
200
201
202

    // 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()) {
203
204
      $element['uri']['#type'] = 'entity_autocomplete';
      // @todo The user should be able to select an entity type. Will be fixed
205
      //   in https://www.drupal.org/node/2423093.
206
207
208
      $element['uri']['#target_type'] = 'node';
      // Disable autocompletion when the first character is '/', '#' or '?'.
      $element['uri']['#attributes']['data-autocomplete-first-character-blacklist'] = '/#?';
209
210
211
212

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

    // If the field is configured to allow only internal links, add a useful
216
    // element prefix and description.
217
    if (!$this->supportsExternalLinks()) {
218
      $element['uri']['#field_prefix'] = rtrim(Url::fromRoute('<front>', [], ['absolute' => TRUE])->toString(), '/');
219
      $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. Enter %nolink to display link text only. Enter %button to display keyboard-accessible link text only.', ['%add-node' => '/node/add', '%front' => '<front>', '%nolink' => '<nolink>', '%button' => '<button>']);
220
221
222
223
    }
    // If the field is configured to allow both internal and external links,
    // show a useful description.
    elseif ($this->supportsExternalLinks() && $this->supportsInternalLinks()) {
224
      $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. Enter %nolink to display link text only. Enter %button to display keyboard-accessible link text only.', ['%front' => '<front>', '%add-node' => '/node/add', '%url' => 'http://example.com', '%nolink' => '<nolink>', '%button' => '<button>']);
225
    }
226
227
228
    // If the field is configured to allow only external links, show a useful
    // description.
    elseif ($this->supportsExternalLinks() && !$this->supportsInternalLinks()) {
229
      $element['uri']['#description'] = $this->t('This must be an external URL such as %url.', ['%url' => 'http://example.com']);
230
    }
231

232
233
234
235
236
237
238
239
240
241
242
243
244
245
    // Make uri required on the front-end when title filled-in.
    if (!$this->isDefaultValueWidget($form_state) && $this->getFieldSetting('title') !== DRUPAL_DISABLED && !$element['uri']['#required']) {
      $parents = $element['#field_parents'];
      $parents[] = $this->fieldDefinition->getName();
      $selector = $root = array_shift($parents);
      if ($parents) {
        $selector = $root . '[' . implode('][', $parents) . ']';
      }

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

246
    $element['title'] = [
247
      '#type' => 'textfield',
248
      '#title' => $this->t('Link text'),
249
      '#placeholder' => $this->getSetting('placeholder_title'),
250
      '#default_value' => $items[$delta]->title ?? NULL,
251
      '#maxlength' => 255,
252
      '#access' => $this->getFieldSetting('title') != DRUPAL_DISABLED,
253
      '#required' => $this->getFieldSetting('title') === DRUPAL_REQUIRED && $element['#required'],
254
    ];
255
256
257
    // 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.
258
259
260
    //
    // Validate that title field is filled out (regardless of uri) when it is a
    // required field.
261
    if (!$this->isDefaultValueWidget($form_state) && $this->getFieldSetting('title') === DRUPAL_REQUIRED) {
262
263
      $element['#element_validate'][] = [static::class, 'validateTitleElement'];
      $element['#element_validate'][] = [static::class, 'validateTitleNoLink'];
264
265
266
267
268

      if (!$element['title']['#required']) {
        // Make title required on the front-end when URI filled-in.

        $parents = $element['#field_parents'];
269
        $parents[] = $this->fieldDefinition->getName();
270
271
272
273
274
275
        $selector = $root = array_shift($parents);
        if ($parents) {
          $selector = $root . '[' . implode('][', $parents) . ']';
        }

        $element['title']['#states']['required'] = [
276
          ':input[name="' . $selector . '[' . $delta . '][uri]"]' => ['filled' => TRUE],
277
278
        ];
      }
279
280
    }

281
282
283
    // Ensure that a URI is always entered when an optional title field is
    // submitted.
    if (!$this->isDefaultValueWidget($form_state) && $this->getFieldSetting('title') == DRUPAL_OPTIONAL) {
284
      $element['#element_validate'][] = [static::class, 'validateTitleNoLink'];
285
286
    }

287
288
    // Exposing the attributes array in the widget is left for alternate and more
    // advanced field widgets.
289
    $element['attributes'] = [
290
291
      '#type' => 'value',
      '#tree' => TRUE,
292
293
294
      '#value' => !empty($items[$delta]->options['attributes']) ? $items[$delta]->options['attributes'] : [],
      '#attributes' => ['class' => ['link-field-widget-attributes']],
    ];
295

296
    // If cardinality is 1, ensure a proper label is output for the field.
297
    if ($this->fieldDefinition->getFieldStorageDefinition()->getCardinality() == 1) {
298
299
300
301
      // 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'];
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
        // 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'],
              ],
            ];
          }
        }
325
326
327
      }
      // Otherwise wrap everything in a details element.
      else {
328
        $element += [
329
          '#type' => 'fieldset',
330
        ];
331
      }
332
333
334
335
336
    }

    return $element;
  }

337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
  /**
   * 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);
  }

361
362
363
  /**
   * {@inheritdoc}
   */
364
  public function settingsForm(array $form, FormStateInterface $form_state) {
365
366
    $elements = parent::settingsForm($form, $form_state);

367
    $elements['placeholder_url'] = [
368
      '#type' => 'textfield',
369
      '#title' => $this->t('Placeholder for URL'),
370
      '#default_value' => $this->getSetting('placeholder_url'),
371
      '#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.'),
372
373
    ];
    $elements['placeholder_title'] = [
374
      '#type' => 'textfield',
375
      '#title' => $this->t('Placeholder for link text'),
376
      '#default_value' => $this->getSetting('placeholder_title'),
377
      '#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.'),
378
379
380
381
382
383
      '#states' => [
        'invisible' => [
          ':input[name="instance[settings][title]"]' => ['value' => DRUPAL_DISABLED],
        ],
      ],
    ];
384
385
386
387

    return $elements;
  }

388
389
390
391
  /**
   * {@inheritdoc}
   */
  public function settingsSummary() {
392
    $summary = [];
393
394
395
396

    $placeholder_title = $this->getSetting('placeholder_title');
    $placeholder_url = $this->getSetting('placeholder_url');
    if (empty($placeholder_title) && empty($placeholder_url)) {
397
      $summary[] = $this->t('No placeholders');
398
399
400
    }
    else {
      if (!empty($placeholder_title)) {
401
        $summary[] = $this->t('Title placeholder: @placeholder_title', ['@placeholder_title' => $placeholder_title]);
402
403
      }
      if (!empty($placeholder_url)) {
404
        $summary[] = $this->t('URL placeholder: @placeholder_url', ['@placeholder_url' => $placeholder_url]);
405
406
407
408
409
410
      }
    }

    return $summary;
  }

411
412
413
  /**
   * {@inheritdoc}
   */
414
  public function massageFormValues(array $values, array $form, FormStateInterface $form_state) {
415
    foreach ($values as &$value) {
416
417
      $value['uri'] = static::getUserEnteredStringAsUri($value['uri']);
      $value += ['options' => []];
418
419
420
421
    }
    return $values;
  }

422
423
424
  /**
   * {@inheritdoc}
   *
425
   * Override the '%uri' message parameter, to ensure that 'internal:' URIs
426
427
428
429
430
   * 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) {
431
      $parameters = $violation->getParameters();
432
433
      if (isset($parameters['@uri'])) {
        $parameters['@uri'] = static::getUriAsDisplayableString($parameters['@uri']);
434
435
436
437
438
439
440
        $violations->set($offset, new ConstraintViolation(
          $this->t($violation->getMessageTemplate(), $parameters),
          $violation->getMessageTemplate(),
          $parameters,
          $violation->getRoot(),
          $violation->getPropertyPath(),
          $violation->getInvalidValue(),
441
          $violation->getPlural(),
442
443
444
445
446
447
448
          $violation->getCode()
        ));
      }
    }
    parent::flagErrors($items, $violations, $form, $form_state);
  }

449
}