LinkFieldTest.php 29.7 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 28 29 30 31 32
  public static $modules = [
    '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 124 125 126 127
      '/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',

      // @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',
128
      '<front>?example=llama' => '&lt;front&gt;?example=llama',
129 130 131 132 133 134 135 136 137 138

      // 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.
139
      'entity:node/' . $restricted_node->id() => '- Restricted access - (' . $restricted_node->id() . ')',
140 141
      // URI for an entity that doesn't exist, but with a valid ID.
      'entity:user/999999' => 'entity:user/999999',
142
    ];
143

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

    // 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.
166
    $this->field->setSetting('link_type', LinkItemInterface::LINK_EXTERNAL);
167
    $this->field->save();
168 169 170 171
    $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.
172
    $this->field->setSetting('link_type', LinkItemInterface::LINK_INTERNAL);
173
    $this->field->save();
174 175
    $this->assertValidEntries($field_name, $valid_internal_entries);
    $this->assertInvalidEntries($field_name, $valid_external_entries + $invalid_internal_entries);
176 177 178 179 180 181 182 183

    // 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]);
184 185 186 187 188 189 190 191 192 193 194
  }

  /**
   * 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) {
195
    foreach ($valid_entries as $uri => $string) {
196
      $edit = [
197
        "{$field_name}[0][uri]" => $uri,
198
      ];
199
      $this->drupalPostForm('entity_test/add', $edit, t('Save'));
200
      preg_match('|entity_test/manage/(\d+)|', $this->getUrl(), $match);
201
      $id = $match[1];
202
      $this->assertText(t('entity_test @id has been created.', ['@id' => $id]));
203
      $this->assertRaw($string);
204 205 206 207 208 209 210 211 212 213 214 215
    }
  }

  /**
   * 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) {
216
    foreach ($invalid_entries as $invalid_value => $error_message) {
217
      $edit = [
218
        "{$field_name}[0][uri]" => $invalid_value,
219
      ];
220
      $this->drupalPostForm('entity_test/add', $edit, t('Save'));
221
      $this->assertText(t($error_message, ['@link_path' => $invalid_value]));
222 223 224 225
    }
  }

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

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

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

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

283
        $this->assertFieldByName("{$field_name}[0][title]", '', 'Link text field found.');
284 285 286 287 288 289 290 291
        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')]));
        }
292
        if ($title_setting === DRUPAL_REQUIRED) {
293
          // Verify that the link text is required, if the URL is non-empty.
294
          $edit = [
295
            "{$field_name}[0][uri]" => 'http://www.example.com',
296
          ];
297
          $this->drupalPostForm(NULL, $edit, t('Save'));
298
          $this->assertText(t('@title field is required if there is @uri input.', ['@title' => t('Link text'), '@uri' => t('URL')]));
299

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

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

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

330 331 332
    $output = $this->renderTestEntity($id);
    $expected_link = (string) \Drupal::l($value, Url::fromUri($value));
    $this->assertContains($expected_link, $output);
333

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

342 343 344
    $output = $this->renderTestEntity($id);
    $expected_link = (string) \Drupal::l($title, Url::fromUri($value));
    $this->assertContains($expected_link, $output);
345 346 347 348 349
  }

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

382
    // Create an entity with three link field values:
383
    // - The first field item uses a URL only.
384
    // - The second field item uses a URL and link text.
385
    // - The third field item uses a fragment-only URL with text.
386 387
    // For consistency in assertion code below, the URL is assigned to the title
    // variable for the first field.
388
    $this->drupalGet('entity_test/add');
389 390
    $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';
391
    $url3 = '#net';
392 393 394
    $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';
395
    $title3 = 'Fragment only';
396
    $edit = [
397
      "{$field_name}[0][uri]" => $url1,
398
      // Note that $title1 is not submitted.
399
      "{$field_name}[0][title]" => '',
400
      "{$field_name}[1][uri]" => $url2,
401
      "{$field_name}[1][title]" => $title2,
402 403
      "{$field_name}[2][uri]" => $url3,
      "{$field_name}[2][title]" => $title3,
404
    ];
405 406
    // Assert label is shown.
    $this->assertText('Read more about this entity');
407
    $this->drupalPostForm(NULL, $edit, t('Save'));
408
    preg_match('|entity_test/manage/(\d+)|', $this->getUrl(), $match);
409
    $id = $match[1];
410
    $this->assertText(t('entity_test @id has been created.', ['@id' => $id]));
411 412 413 414

    // 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
415 416
    // the link generator and options/attributes. Only 'url_plain' has a
    // dependency on 'url_only', so we have a total of ~10 cases.
417 418 419 420 421 422 423 424 425 426 427
    $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],
      ],
    ];
428 429 430 431
    foreach ($options as $setting => $values) {
      foreach ($values as $new_value) {
        // Update the field formatter settings.
        if (!is_array($new_value)) {
432
          $display_options['settings'] = [$setting => $new_value];
433 434
        }
        else {
435
          $display_options['settings'] = $new_value;
436
        }
437
        entity_get_display('entity_test', 'entity_test', 'full')
438
          ->setComponent($field_name, $display_options)
439
          ->save();
440

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

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

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

          case 'rel':
            $rel = isset($new_value) ? ' rel="' . $new_value . '"' : '';
459 460 461
            $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);
462 463 464 465
            break;

          case 'target':
            $target = isset($new_value) ? ' target="' . $new_value . '"' : '';
466 467 468
            $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);
469 470 471 472 473
            break;

          case 'url_only':
            // In this case, $new_value is an array.
            if (!$new_value['url_only']) {
474 475 476
              $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);
477 478 479
            }
            else {
              if (empty($new_value['url_plain'])) {
480 481 482
                $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);
483 484
              }
              else {
485 486 487 488 489 490
                $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);
491 492 493 494 495 496 497 498 499 500 501 502 503 504
              }
            }
            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.
   */
505
  public function testLinkSeparateFormatter() {
506
    $field_name = mb_strtolower($this->randomMachineName());
507
    // Create a field with settings to validate.
508
    $this->fieldStorage = FieldStorageConfig::create([
509
      'field_name' => $field_name,
510
      'entity_type' => 'entity_test',
511
      'type' => 'link',
512
      'cardinality' => 3,
513
    ]);
514
    $this->fieldStorage->save();
515
    FieldConfig::create([
516
      'field_storage' => $this->fieldStorage,
517
      'bundle' => 'entity_test',
518
      'settings' => [
519
        'title' => DRUPAL_OPTIONAL,
520
        'link_type' => LinkItemInterface::LINK_GENERIC,
521
      ],
522
    ])->save();
523
    $display_options = [
524 525
      'type' => 'link_separate',
      'label' => 'hidden',
526
    ];
527
    entity_get_form_display('entity_test', 'entity_test', 'default')
528
      ->setComponent($field_name, [
529
        'type' => 'link_default',
530
      ])
531
      ->save();
532
    entity_get_display('entity_test', 'entity_test', 'full')
533
      ->setComponent($field_name, $display_options)
534 535
      ->save();

536
    // Create an entity with three link field values:
537
    // - The first field item uses a URL only.
538
    // - The second field item uses a URL and link text.
539
    // - The third field item uses a fragment-only URL with text.
540 541
    // For consistency in assertion code below, the URL is assigned to the title
    // variable for the first field.
542
    $this->drupalGet('entity_test/add');
543 544
    $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';
545
    $url3 = '#net';
546 547
    // 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';
548
    $title3 = 'Fragment only';
549
    $edit = [
550 551
      "{$field_name}[0][uri]" => $url1,
      "{$field_name}[1][uri]" => $url2,
552
      "{$field_name}[1][title]" => $title2,
553 554
      "{$field_name}[2][uri]" => $url3,
      "{$field_name}[2][title]" => $title3,
555
    ];
556
    $this->drupalPostForm(NULL, $edit, t('Save'));
557
    preg_match('|entity_test/manage/(\d+)|', $this->getUrl(), $match);
558
    $id = $match[1];
559
    $this->assertText(t('entity_test @id has been created.', ['@id' => $id]));
560 561

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

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

            $url = $url2;
586 587
            $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;
588
            $expected = '<div class="link-item">';
589 590
            $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>';
591
            $expected .= '</div>';
592
            $this->assertContains($expected, $output);
593 594 595 596 597 598 599 600

            $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>';
601
            $this->assertContains($expected, $output);
602 603 604 605
            break;

          case 'rel':
            $rel = isset($new_value) ? ' rel="' . $new_value . '"' : '';
606 607 608
            $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);
609 610 611 612
            break;

          case 'target':
            $target = isset($new_value) ? ' target="' . $new_value . '"' : '';
613 614 615
            $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);
616 617 618 619 620 621
            break;
        }
      }
    }
  }

622 623 624 625 626 627 628 629 630 631 632
  /**
   * 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;
633
    $field_name = mb_strtolower($this->randomMachineName());
634 635 636 637 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

    // 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);
  }

665 666 667 668 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
  /**
   * 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);
  }

725
  /**
726
   * Renders a test_entity and returns the output.
727 728 729 730 731 732
   *
   * @param int $id
   *   The test_entity ID to render.
   * @param string $view_mode
   *   (optional) The view mode to use for rendering.
   * @param bool $reset
733
   *   (optional) Whether to reset the entity_test storage cache. Defaults to
734
   *   TRUE to simplify testing.
735 736 737
   *
   * @return string
   *   The rendered HTML output.
738 739 740