LinkFieldTest.php 29.8 KB
Newer Older
1 2
<?php

3
namespace Drupal\Tests\link\Functional;
4

5
use Drupal\Component\Utility\Html;
6
use Drupal\Component\Utility\Unicode;
7
use Drupal\Core\Url;
8
use Drupal\entity_test\Entity\EntityTest;
9
use Drupal\field\Entity\FieldConfig;
10
use Drupal\link\LinkItemInterface;
11
use Drupal\node\NodeInterface;
12
use Drupal\Tests\BrowserTestBase;
13
use Drupal\field\Entity\FieldStorageConfig;
14 15 16

/**
 * Tests link field widgets and formatters.
17 18
 *
 * @group link
19
 */
20
class LinkFieldTest extends BrowserTestBase {
21 22 23 24 25 26

  /**
   * Modules to enable.
   *
   * @var array
   */
27
  public static $modules = [
28 29 30 31 32
    'entity_test',
    'link',
    'node',
    'link_test_base_field',
  ];
33

34 35 36
  /**
   * A field to use in this test class.
   *
37
   * @var \Drupal\field\Entity\FieldStorageConfig
38
   */
39
  protected $fieldStorage;
40 41 42 43

  /**
   * The instance used in this test class.
   *
44
   * @var \Drupal\field\Entity\FieldConfig
45
   */
46
  protected $field;
47

48
  protected function setUp() {
49 50
    parent::setUp();

51
    $this->drupalLogin($this->drupalCreateUser([
52 53
      'view test entity',
      'administer entity_test content',
54
      'link to any page',
55
    ]));
56 57 58 59 60
  }

  /**
   * Tests link field URL validation.
   */
61
  public function testURLValidation() {
62
    $field_name = mb_strtolower($this->randomMachineName());
63
    // Create a field with settings to validate.
64
    $this->fieldStorage = FieldStorageConfig::create([
65
      'field_name' => $field_name,
66
      'entity_type' => 'entity_test',
67
      'type' => 'link',
68
    ]);
69
    $this->fieldStorage->save();
70
    $this->field = FieldConfig::create([
71
      'field_storage' => $this->fieldStorage,
72
      'bundle' => 'entity_test',
73
      'settings' => [
74
        'title' => DRUPAL_DISABLED,
75
        'link_type' => LinkItemInterface::LINK_GENERIC,
76
      ],
77
    ]);
78
    $this->field->save();
79
    entity_get_form_display('entity_test', 'entity_test', 'default')
80
      ->setComponent($field_name, [
81
        'type' => 'link_default',
82
        'settings' => [
83
          'placeholder_url' => 'http://example.com',
84 85
        ],
      ])
86
      ->save();
87
    entity_get_display('entity_test', 'entity_test', 'full')
88
      ->setComponent($field_name, [
89
        'type' => 'link',
90
      ])
91 92
      ->save();

93
    // Display creation form.
94
    $this->drupalGet('entity_test/add');
95
    $this->assertFieldByName("{$field_name}[0][uri]", '', 'Link URL field is displayed');
96
    $this->assertRaw('placeholder="http://example.com"');
97

98
    // Create a path alias.
99
    \Drupal::service('path.alias_storage')->save('/admin', '/a/path/alias');
100 101 102 103

    // Create a node to test the link widget.
    $node = $this->drupalCreateNode();

104
    $restricted_node = $this->drupalCreateNode(['status' => NodeInterface::NOT_PUBLISHED]);
105

106 107
    // Define some valid URLs (keys are the entered values, values are the
    // strings displayed to the user).
108
    $valid_external_entries = [
109
      'http://www.example.com/' => 'http://www.example.com/',
110 111 112 113
      // Strings within parenthesis without leading space char.
      'http://www.example.com/strings_(string_within_parenthesis)' => 'http://www.example.com/strings_(string_within_parenthesis)',
      // Numbers within parenthesis without leading space char.
      'http://www.example.com/numbers_(9999)' => 'http://www.example.com/numbers_(9999)',
114 115
    ];
    $valid_internal_entries = [
116 117 118 119 120 121 122 123
      '/entity_test/add' => '/entity_test/add',
      '/a/path/alias' => '/a/path/alias',

      // Front page, with query string and fragment.
      '/' => '&lt;front&gt;',
      '/?example=llama' => '&lt;front&gt;?example=llama',
      '/#example' => '&lt;front&gt;#example',

124 125 126 127
      // Trailing spaces should be ignored.
      '/ ' => '&lt;front&gt;',
      '/path with spaces ' => '/path with spaces',

128 129 130 131
      // @todo '<front>' is valid input for BC reasons, may be removed by
      //   https://www.drupal.org/node/2421941
      '<front>' => '&lt;front&gt;',
      '<front>#example' => '&lt;front&gt;#example',
132
      '<front>?example=llama' => '&lt;front&gt;?example=llama',
133 134 135 136 137 138 139 140 141 142

      // Query string and fragment.
      '?example=llama' => '?example=llama',
      '#example' => '#example',

      // Entity reference autocomplete value.
      $node->label() . ' (1)' => $node->label() . ' (1)',
      // Entity URI displayed as ER autocomplete value when displayed in a form.
      'entity:node/1' => $node->label() . ' (1)',
      // URI for an entity that exists, but is not accessible by the user.
143
      'entity:node/' . $restricted_node->id() => '- Restricted access - (' . $restricted_node->id() . ')',
144 145
      // URI for an entity that doesn't exist, but with a valid ID.
      'entity:user/999999' => 'entity:user/999999',
146
    ];
147

148
    // Define some invalid URLs.
149
    $validation_error_1 = "The path '@link_path' is invalid.";
150
    $validation_error_2 = 'Manually entered paths should start with /, ? or #.';
151
    $validation_error_3 = "The path '@link_path' is inaccessible.";
152
    $invalid_external_entries = [
153
      // Invalid protocol
154
      'invalid://not-a-valid-protocol' => $validation_error_1,
155
      // Missing host name
156
      'http://' => $validation_error_1,
157 158
    ];
    $invalid_internal_entries = [
159 160
      'no-leading-slash' => $validation_error_2,
      'entity:non_existing_entity_type/yar' => $validation_error_1,
161 162
      // URI for an entity that doesn't exist, with an invalid ID.
      'entity:user/invalid-parameter' => $validation_error_1,
163
    ];
164 165 166 167 168 169

    // Test external and internal URLs for 'link_type' = LinkItemInterface::LINK_GENERIC.
    $this->assertValidEntries($field_name, $valid_external_entries + $valid_internal_entries);
    $this->assertInvalidEntries($field_name, $invalid_external_entries + $invalid_internal_entries);

    // Test external URLs for 'link_type' = LinkItemInterface::LINK_EXTERNAL.
170
    $this->field->setSetting('link_type', LinkItemInterface::LINK_EXTERNAL);
171
    $this->field->save();
172 173 174 175
    $this->assertValidEntries($field_name, $valid_external_entries);
    $this->assertInvalidEntries($field_name, $valid_internal_entries + $invalid_external_entries);

    // Test external URLs for 'link_type' = LinkItemInterface::LINK_INTERNAL.
176
    $this->field->setSetting('link_type', LinkItemInterface::LINK_INTERNAL);
177
    $this->field->save();
178 179
    $this->assertValidEntries($field_name, $valid_internal_entries);
    $this->assertInvalidEntries($field_name, $valid_external_entries + $invalid_internal_entries);
180 181 182 183 184 185 186 187

    // Ensure that users with 'link to any page', don't apply access checking.
    $this->drupalLogin($this->drupalCreateUser([
      'view test entity',
      'administer entity_test content',
    ]));
    $this->assertValidEntries($field_name, ['/entity_test/add' => '/entity_test/add']);
    $this->assertInValidEntries($field_name, ['/admin' => $validation_error_3]);
188 189 190 191 192 193 194 195 196 197 198
  }

  /**
   * Asserts that valid URLs can be submitted.
   *
   * @param string $field_name
   *   The field name.
   * @param array $valid_entries
   *   An array of valid URL entries.
   */
  protected function assertValidEntries($field_name, array $valid_entries) {
199
    foreach ($valid_entries as $uri => $string) {
200
      $edit = [
201
        "{$field_name}[0][uri]" => $uri,
202
      ];
203
      $this->drupalPostForm('entity_test/add', $edit, t('Save'));
204
      preg_match('|entity_test/manage/(\d+)|', $this->getUrl(), $match);
205
      $id = $match[1];
206
      $this->assertText(t('entity_test @id has been created.', ['@id' => $id]));
207
      $this->assertRaw('"' . $string . '"');
208 209 210 211 212 213 214 215 216 217 218 219
    }
  }

  /**
   * Asserts that invalid URLs cannot be submitted.
   *
   * @param string $field_name
   *   The field name.
   * @param array $invalid_entries
   *   An array of invalid URL entries.
   */
  protected function assertInvalidEntries($field_name, array $invalid_entries) {
220
    foreach ($invalid_entries as $invalid_value => $error_message) {
221
      $edit = [
222
        "{$field_name}[0][uri]" => $invalid_value,
223
      ];
224
      $this->drupalPostForm('entity_test/add', $edit, t('Save'));
225
      $this->assertText(t($error_message, ['@link_path' => $invalid_value]));
226 227 228 229
    }
  }

  /**
230
   * Tests the link title settings of a link field.
231
   */
232
  public function testLinkTitle() {
233
    $field_name = mb_strtolower($this->randomMachineName());
234
    // Create a field with settings to validate.
235
    $this->fieldStorage = FieldStorageConfig::create([
236
      'field_name' => $field_name,
237
      'entity_type' => 'entity_test',
238
      'type' => 'link',
239
    ]);
240
    $this->fieldStorage->save();
241
    $this->field = FieldConfig::create([
242
      'field_storage' => $this->fieldStorage,
243
      'bundle' => 'entity_test',
244
      'label' => 'Read more about this entity',
245
      'settings' => [
246
        'title' => DRUPAL_OPTIONAL,
247
        'link_type' => LinkItemInterface::LINK_GENERIC,
248
      ],
249
    ]);
250
    $this->field->save();
251
    entity_get_form_display('entity_test', 'entity_test', 'default')
252
      ->setComponent($field_name, [
253
        'type' => 'link_default',
254
        'settings' => [
255
          'placeholder_url' => 'http://example.com',
256
          'placeholder_title' => 'Enter the text for this link',
257 258
        ],
      ])
259
      ->save();
260
    entity_get_display('entity_test', 'entity_test', 'full')
261
      ->setComponent($field_name, [
262 263
        'type' => 'link',
        'label' => 'hidden',
264
      ])
265 266
      ->save();

267
    // Verify that the link text field works according to the field setting.
268
    foreach ([DRUPAL_DISABLED, DRUPAL_REQUIRED, DRUPAL_OPTIONAL] as $title_setting) {
269
      // Update the link title field setting.
270
      $this->field->setSetting('title', $title_setting);
271
      $this->field->save();
272 273

      // Display creation form.
274
      $this->drupalGet('entity_test/add');
275 276
      // Assert label is shown.
      $this->assertText('Read more about this entity');
277
      $this->assertFieldByName("{$field_name}[0][uri]", '', 'URL field found.');
278
      $this->assertRaw('placeholder="http://example.com"');
279 280

      if ($title_setting === DRUPAL_DISABLED) {
281
        $this->assertNoFieldByName("{$field_name}[0][title]", '', 'Link text field not found.');
282
        $this->assertNoRaw('placeholder="Enter the text for this link"');
283 284
      }
      else {
285
        $this->assertRaw('placeholder="Enter the text for this link"');
286

287
        $this->assertFieldByName("{$field_name}[0][title]", '', 'Link text field found.');
288 289 290 291 292 293 294 295
        if ($title_setting === DRUPAL_OPTIONAL) {
          // Verify that the URL is required, if the link text is non-empty.
          $edit = [
            "{$field_name}[0][title]" => 'Example',
          ];
          $this->drupalPostForm(NULL, $edit, t('Save'));
          $this->assertText(t('The URL field is required when the @title field is specified.', ['@title' => t('Link text')]));
        }
296
        if ($title_setting === DRUPAL_REQUIRED) {
297
          // Verify that the link text is required, if the URL is non-empty.
298
          $edit = [
299
            "{$field_name}[0][uri]" => 'http://www.example.com',
300
          ];
301
          $this->drupalPostForm(NULL, $edit, t('Save'));
302
          $this->assertText(t('@title field is required if there is @uri input.', ['@title' => t('Link text'), '@uri' => t('URL')]));
303

304
          // Verify that the link text is not required, if the URL is empty.
305
          $edit = [
306
            "{$field_name}[0][uri]" => '',
307
          ];
308
          $this->drupalPostForm(NULL, $edit, t('Save'));
309
          $this->assertNoText(t('@name field is required.', ['@name' => t('Link text')]));
310

311
          // Verify that a URL and link text meets requirements.
312
          $this->drupalGet('entity_test/add');
313
          $edit = [
314
            "{$field_name}[0][uri]" => 'http://www.example.com',
315
            "{$field_name}[0][title]" => 'Example',
316
          ];
317
          $this->drupalPostForm(NULL, $edit, t('Save'));
318
          $this->assertNoText(t('@name field is required.', ['@name' => t('Link text')]));
319 320 321 322
        }
      }
    }

323
    // Verify that a link without link text is rendered using the URL as text.
324
    $value = 'http://www.example.com/';
325
    $edit = [
326
      "{$field_name}[0][uri]" => $value,
327
      "{$field_name}[0][title]" => '',
328
    ];
329
    $this->drupalPostForm(NULL, $edit, t('Save'));
330
    preg_match('|entity_test/manage/(\d+)|', $this->getUrl(), $match);
331
    $id = $match[1];
332
    $this->assertText(t('entity_test @id has been created.', ['@id' => $id]));
333

334 335 336
    $output = $this->renderTestEntity($id);
    $expected_link = (string) \Drupal::l($value, Url::fromUri($value));
    $this->assertContains($expected_link, $output);
337

338
    // Verify that a link with text is rendered using the link text.
339
    $title = $this->randomMachineName();
340
    $edit = [
341
      "{$field_name}[0][title]" => $title,
342
    ];
343
    $this->drupalPostForm("entity_test/manage/$id/edit", $edit, t('Save'));
344
    $this->assertText(t('entity_test @id has been updated.', ['@id' => $id]));
345

346 347 348
    $output = $this->renderTestEntity($id);
    $expected_link = (string) \Drupal::l($title, Url::fromUri($value));
    $this->assertContains($expected_link, $output);
349 350 351 352 353
  }

  /**
   * Tests the default 'link' formatter.
   */
354
  public function testLinkFormatter() {
355
    $field_name = mb_strtolower($this->randomMachineName());
356
    // Create a field with settings to validate.
357
    $this->fieldStorage = FieldStorageConfig::create([
358
      'field_name' => $field_name,
359
      'entity_type' => 'entity_test',
360
      'type' => 'link',
361
      'cardinality' => 3,
362
    ]);
363
    $this->fieldStorage->save();
364
    FieldConfig::create([
365
      'field_storage' => $this->fieldStorage,
366
      'label' => 'Read more about this entity',
367
      'bundle' => 'entity_test',
368
      'settings' => [
369
        'title' => DRUPAL_OPTIONAL,
370
        'link_type' => LinkItemInterface::LINK_GENERIC,
371
      ],
372
    ])->save();
373
    entity_get_form_display('entity_test', 'entity_test', 'default')
374
      ->setComponent($field_name, [
375
        'type' => 'link_default',
376
      ])
377
      ->save();
378
    $display_options = [
379 380
      'type' => 'link',
      'label' => 'hidden',
381
    ];
382
    entity_get_display('entity_test', 'entity_test', 'full')
383
      ->setComponent($field_name, $display_options)
384 385
      ->save();

386
    // Create an entity with three link field values:
387
    // - The first field item uses a URL only.
388
    // - The second field item uses a URL and link text.
389
    // - The third field item uses a fragment-only URL with text.
390 391
    // For consistency in assertion code below, the URL is assigned to the title
    // variable for the first field.
392
    $this->drupalGet('entity_test/add');
393 394
    $url1 = 'http://www.example.com/content/articles/archive?author=John&year=2012#com';
    $url2 = 'http://www.example.org/content/articles/archive?author=John&year=2012#org';
395
    $url3 = '#net';
396 397 398
    $title1 = $url1;
    // Intentionally contains an ampersand that needs sanitization on output.
    $title2 = 'A very long & strange example title that could break the nice layout of the site';
399
    $title3 = 'Fragment only';
400
    $edit = [
401
      "{$field_name}[0][uri]" => $url1,
402
      // Note that $title1 is not submitted.
403
      "{$field_name}[0][title]" => '',
404
      "{$field_name}[1][uri]" => $url2,
405
      "{$field_name}[1][title]" => $title2,
406 407
      "{$field_name}[2][uri]" => $url3,
      "{$field_name}[2][title]" => $title3,
408
    ];
409 410
    // Assert label is shown.
    $this->assertText('Read more about this entity');
411
    $this->drupalPostForm(NULL, $edit, t('Save'));
412
    preg_match('|entity_test/manage/(\d+)|', $this->getUrl(), $match);
413
    $id = $match[1];
414
    $this->assertText(t('entity_test @id has been created.', ['@id' => $id]));
415 416 417 418

    // Verify that the link is output according to the formatter settings.
    // Not using generatePermutations(), since that leads to 32 cases, which
    // would not test actual link field formatter functionality but rather
419 420
    // the link generator and options/attributes. Only 'url_plain' has a
    // dependency on 'url_only', so we have a total of ~10 cases.
421 422 423 424 425 426 427 428 429 430 431
    $options = [
      'trim_length' => [NULL, 6],
      'rel' => [NULL, 'nofollow'],
      'target' => [NULL, '_blank'],
      'url_only' => [
        ['url_only' => FALSE],
        ['url_only' => FALSE, 'url_plain' => TRUE],
        ['url_only' => TRUE],
        ['url_only' => TRUE, 'url_plain' => TRUE],
      ],
    ];
432 433 434 435
    foreach ($options as $setting => $values) {
      foreach ($values as $new_value) {
        // Update the field formatter settings.
        if (!is_array($new_value)) {
436
          $display_options['settings'] = [$setting => $new_value];
437 438
        }
        else {
439
          $display_options['settings'] = $new_value;
440
        }
441
        entity_get_display('entity_test', 'entity_test', 'full')
442
          ->setComponent($field_name, $display_options)
443
          ->save();
444

445
        $output = $this->renderTestEntity($id);
446 447 448
        switch ($setting) {
          case 'trim_length':
            $url = $url1;
449
            $title = isset($new_value) ? Unicode::truncate($title1, $new_value, FALSE, TRUE) : $title1;
450
            $this->assertContains('<a href="' . Html::escape($url) . '">' . Html::escape($title) . '</a>', $output);
451 452

            $url = $url2;
453
            $title = isset($new_value) ? Unicode::truncate($title2, $new_value, FALSE, TRUE) : $title2;
454
            $this->assertContains('<a href="' . Html::escape($url) . '">' . Html::escape($title) . '</a>', $output);
455 456 457

            $url = $url3;
            $title = isset($new_value) ? Unicode::truncate($title3, $new_value, FALSE, TRUE) : $title3;
458
            $this->assertContains('<a href="' . Html::escape($url) . '">' . Html::escape($title) . '</a>', $output);
459 460 461 462
            break;

          case 'rel':
            $rel = isset($new_value) ? ' rel="' . $new_value . '"' : '';
463 464 465
            $this->assertContains('<a href="' . Html::escape($url1) . '"' . $rel . '>' . Html::escape($title1) . '</a>', $output);
            $this->assertContains('<a href="' . Html::escape($url2) . '"' . $rel . '>' . Html::escape($title2) . '</a>', $output);
            $this->assertContains('<a href="' . Html::escape($url3) . '"' . $rel . '>' . Html::escape($title3) . '</a>', $output);
466 467 468 469
            break;

          case 'target':
            $target = isset($new_value) ? ' target="' . $new_value . '"' : '';
470 471 472
            $this->assertContains('<a href="' . Html::escape($url1) . '"' . $target . '>' . Html::escape($title1) . '</a>', $output);
            $this->assertContains('<a href="' . Html::escape($url2) . '"' . $target . '>' . Html::escape($title2) . '</a>', $output);
            $this->assertContains('<a href="' . Html::escape($url3) . '"' . $target . '>' . Html::escape($title3) . '</a>', $output);
473 474 475 476 477
            break;

          case 'url_only':
            // In this case, $new_value is an array.
            if (!$new_value['url_only']) {
478 479 480
              $this->assertContains('<a href="' . Html::escape($url1) . '">' . Html::escape($title1) . '</a>', $output);
              $this->assertContains('<a href="' . Html::escape($url2) . '">' . Html::escape($title2) . '</a>', $output);
              $this->assertContains('<a href="' . Html::escape($url3) . '">' . Html::escape($title3) . '</a>', $output);
481 482 483
            }
            else {
              if (empty($new_value['url_plain'])) {
484 485 486
                $this->assertContains('<a href="' . Html::escape($url1) . '">' . Html::escape($url1) . '</a>', $output);
                $this->assertContains('<a href="' . Html::escape($url2) . '">' . Html::escape($url2) . '</a>', $output);
                $this->assertContains('<a href="' . Html::escape($url3) . '">' . Html::escape($url3) . '</a>', $output);
487 488
              }
              else {
489 490 491 492 493 494
                $this->assertNotContains('<a href="' . Html::escape($url1) . '">' . Html::escape($url1) . '</a>', $output);
                $this->assertNotContains('<a href="' . Html::escape($url2) . '">' . Html::escape($url2) . '</a>', $output);
                $this->assertNotContains('<a href="' . Html::escape($url3) . '">' . Html::escape($url3) . '</a>', $output);
                $this->assertContains(Html::escape($url1), $output);
                $this->assertContains(Html::escape($url2), $output);
                $this->assertContains(Html::escape($url3), $output);
495 496 497 498 499 500 501 502 503 504 505 506 507 508
              }
            }
            break;
        }
      }
    }
  }

  /**
   * Tests the 'link_separate' formatter.
   *
   * This test is mostly the same as testLinkFormatter(), but they cannot be
   * merged, since they involve different configuration and output.
   */
509
  public function testLinkSeparateFormatter() {
510
    $field_name = mb_strtolower($this->randomMachineName());
511
    // Create a field with settings to validate.
512
    $this->fieldStorage = FieldStorageConfig::create([
513
      'field_name' => $field_name,
514
      'entity_type' => 'entity_test',
515
      'type' => 'link',
516
      'cardinality' => 3,
517
    ]);
518
    $this->fieldStorage->save();
519
    FieldConfig::create([
520
      'field_storage' => $this->fieldStorage,
521
      'bundle' => 'entity_test',
522
      'settings' => [
523
        'title' => DRUPAL_OPTIONAL,
524
        'link_type' => LinkItemInterface::LINK_GENERIC,
525
      ],
526
    ])->save();
527
    $display_options = [
528 529
      'type' => 'link_separate',
      'label' => 'hidden',
530
    ];
531
    entity_get_form_display('entity_test', 'entity_test', 'default')
532
      ->setComponent($field_name, [
533
        'type' => 'link_default',
534
      ])
535
      ->save();
536
    entity_get_display('entity_test', 'entity_test', 'full')
537
      ->setComponent($field_name, $display_options)
538 539
      ->save();

540
    // Create an entity with three link field values:
541
    // - The first field item uses a URL only.
542
    // - The second field item uses a URL and link text.
543
    // - The third field item uses a fragment-only URL with text.
544 545
    // For consistency in assertion code below, the URL is assigned to the title
    // variable for the first field.
546
    $this->drupalGet('entity_test/add');
547 548
    $url1 = 'http://www.example.com/content/articles/archive?author=John&year=2012#com';
    $url2 = 'http://www.example.org/content/articles/archive?author=John&year=2012#org';
549
    $url3 = '#net';
550 551
    // Intentionally contains an ampersand that needs sanitization on output.
    $title2 = 'A very long & strange example title that could break the nice layout of the site';
552
    $title3 = 'Fragment only';
553
    $edit = [
554 555
      "{$field_name}[0][uri]" => $url1,
      "{$field_name}[1][uri]" => $url2,
556
      "{$field_name}[1][title]" => $title2,
557 558
      "{$field_name}[2][uri]" => $url3,
      "{$field_name}[2][title]" => $title3,
559
    ];
560
    $this->drupalPostForm(NULL, $edit, t('Save'));
561
    preg_match('|entity_test/manage/(\d+)|', $this->getUrl(), $match);
562
    $id = $match[1];
563
    $this->assertText(t('entity_test @id has been created.', ['@id' => $id]));
564 565

    // Verify that the link is output according to the formatter settings.
566 567 568 569 570
    $options = [
      'trim_length' => [NULL, 6],
      'rel' => [NULL, 'nofollow'],
      'target' => [NULL, '_blank'],
    ];
571 572 573
    foreach ($options as $setting => $values) {
      foreach ($values as $new_value) {
        // Update the field formatter settings.
574
        $display_options['settings'] = [$setting => $new_value];
575
        entity_get_display('entity_test', 'entity_test', 'full')
576
          ->setComponent($field_name, $display_options)
577
          ->save();
578

579
        $output = $this->renderTestEntity($id);
580 581 582
        switch ($setting) {
          case 'trim_length':
            $url = $url1;
583
            $url_title = isset($new_value) ? Unicode::truncate($url, $new_value, FALSE, TRUE) : $url;
584
            $expected = '<div class="link-item">';
585
            $expected .= '<div class="link-url"><a href="' . Html::escape($url) . '">' . Html::escape($url_title) . '</a></div>';
586
            $expected .= '</div>';
587
            $this->assertContains($expected, $output);
588 589

            $url = $url2;
590 591
            $url_title = isset($new_value) ? Unicode::truncate($url, $new_value, FALSE, TRUE) : $url;
            $title = isset($new_value) ? Unicode::truncate($title2, $new_value, FALSE, TRUE) : $title2;
592
            $expected = '<div class="link-item">';
593 594
            $expected .= '<div class="link-title">' . Html::escape($title) . '</div>';
            $expected .= '<div class="link-url"><a href="' . Html::escape($url) . '">' . Html::escape($url_title) . '</a></div>';
595
            $expected .= '</div>';
596
            $this->assertContains($expected, $output);
597 598 599 600 601 602 603 604

            $url = $url3;
            $url_title = isset($new_value) ? Unicode::truncate($url, $new_value, FALSE, TRUE) : $url;
            $title = isset($new_value) ? Unicode::truncate($title3, $new_value, FALSE, TRUE) : $title3;
            $expected = '<div class="link-item">';
            $expected .= '<div class="link-title">' . Html::escape($title) . '</div>';
            $expected .= '<div class="link-url"><a href="' . Html::escape($url) . '">' . Html::escape($url_title) . '</a></div>';
            $expected .= '</div>';
605
            $this->assertContains($expected, $output);
606 607 608 609
            break;

          case 'rel':
            $rel = isset($new_value) ? ' rel="' . $new_value . '"' : '';
610 611 612
            $this->assertContains('<div class="link-url"><a href="' . Html::escape($url1) . '"' . $rel . '>' . Html::escape($url1) . '</a></div>', $output);
            $this->assertContains('<div class="link-url"><a href="' . Html::escape($url2) . '"' . $rel . '>' . Html::escape($url2) . '</a></div>', $output);
            $this->assertContains('<div class="link-url"><a href="' . Html::escape($url3) . '"' . $rel . '>' . Html::escape($url3) . '</a></div>', $output);
613 614 615 616
            break;

          case 'target':
            $target = isset($new_value) ? ' target="' . $new_value . '"' : '';
617 618 619
            $this->assertContains('<div class="link-url"><a href="' . Html::escape($url1) . '"' . $target . '>' . Html::escape($url1) . '</a></div>', $output);
            $this->assertContains('<div class="link-url"><a href="' . Html::escape($url2) . '"' . $target . '>' . Html::escape($url2) . '</a></div>', $output);
            $this->assertContains('<div class="link-url"><a href="' . Html::escape($url3) . '"' . $target . '>' . Html::escape($url3) . '</a></div>', $output);
620 621 622 623 624 625
            break;
        }
      }
    }
  }

626 627 628 629 630 631 632 633 634 635 636
  /**
   * Test '#link_type' property exists on 'link_default' widget.
   *
   * Make sure the 'link_default' widget exposes a '#link_type' property on
   * its element. Modules can use it to understand if a text form element is
   * a link and also which LinkItemInterface::LINK_* is (EXTERNAL, GENERIC,
   * INTERNAL).
   */
  public function testLinkTypeOnLinkWidget() {

    $link_type = LinkItemInterface::LINK_EXTERNAL;
637
    $field_name = mb_strtolower($this->randomMachineName());
638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668

    // Create a field with settings to validate.
    $this->fieldStorage = FieldStorageConfig::create([
      'field_name' => $field_name,
      'entity_type' => 'entity_test',
      'type' => 'link',
      'cardinality' => 1,
    ]);
    $this->fieldStorage->save();
    FieldConfig::create([
      'field_storage' => $this->fieldStorage,
      'label' => 'Read more about this entity',
      'bundle' => 'entity_test',
      'settings' => [
        'title' => DRUPAL_OPTIONAL,
        'link_type' => $link_type,
      ],
    ])->save();

    $this->container->get('entity.manager')
      ->getStorage('entity_form_display')
      ->load('entity_test.entity_test.default')
      ->setComponent($field_name, [
        'type' => 'link_default',
      ])
      ->save();

    $form = \Drupal::service('entity.form_builder')->getForm(EntityTest::create());
    $this->assertEqual($form[$field_name]['widget'][0]['uri']['#link_type'], $link_type);
  }

669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728
  /**
   * Tests editing a link to a non-node entity.
   */
  public function testEditNonNodeEntityLink() {

    $entity_type_manager = \Drupal::entityTypeManager();
    $entity_test_storage = $entity_type_manager->getStorage('entity_test');

    // Create a field with settings to validate.
    $this->fieldStorage = FieldStorageConfig::create([
      'field_name' => 'field_link',
      'entity_type' => 'entity_test',
      'type' => 'link',
      'cardinality' => 1,
    ]);
    $this->fieldStorage->save();
    FieldConfig::create([
      'field_storage' => $this->fieldStorage,
      'label' => 'Read more about this entity',
      'bundle' => 'entity_test',
      'settings' => [
        'title' => DRUPAL_OPTIONAL,
      ],
    ])->save();

    $entity_type_manager
      ->getStorage('entity_form_display')
      ->load('entity_test.entity_test.default')
      ->setComponent('field_link', [
        'type' => 'link_default',
      ])
      ->save();

    // Create a node and a test entity to have a possibly valid reference for
    // both. Create another test entity that references the first test entity.
    $entity_test_link = $entity_test_storage->create(['name' => 'correct link target']);
    $entity_test_link->save();

    $node = $this->drupalCreateNode(['wrong link target']);

    $correct_link = 'entity:entity_test/' . $entity_test_link->id();
    $entity_test = $entity_test_storage->create([
      'name' => 'correct link target',
      'field_link' => $correct_link,
    ]);
    $entity_test->save();

    // Edit the entity and save it, verify the correct link is kept and not
    // changed to point to a node. Currently, widget does not support non-node
    // autocomplete and therefore must show the link unaltered.
    $this->drupalGet($entity_test->toUrl('edit-form'));
    $this->assertSession()->fieldValueEquals('field_link[0][uri]', $correct_link);
    $this->drupalPostForm(NULL, [], 'Save');

    $entity_test_storage->resetCache();
    $entity_test = $entity_test_storage->load($entity_test->id());

    $this->assertEquals($correct_link, $entity_test->get('field_link')->uri);
  }

729
  /**
730
   * Renders a test_entity and returns the output.
731 732 733 734 735 736
   *
   * @param int $id
   *   The test_entity ID to render.
   * @param string $view_mode
   *   (optional) The view mode to use for rendering.
   * @param bool $reset
737
   *   (optional) Whether to reset the entity_test storage cache. Defaults to