function LinkFieldTest::testLinkWidgetCaughtExceptionEditingInvalidUrl

Same name in other branches
  1. 11.x core/modules/link/tests/src/Functional/LinkFieldTest.php \Drupal\Tests\link\Functional\LinkFieldTest::testLinkWidgetCaughtExceptionEditingInvalidUrl()

Test link widget exception handled if link uri value is invalid.

File

core/modules/link/tests/src/Functional/LinkFieldTest.php, line 1072

Class

LinkFieldTest
Tests link field widgets and formatters.

Namespace

Drupal\Tests\link\Functional

Code

public function testLinkWidgetCaughtExceptionEditingInvalidUrl() : void {
    $field_name = $this->randomMachineName();
    $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' => 'Link',
        'bundle' => 'entity_test',
        'settings' => [
            'title' => DRUPAL_OPTIONAL,
            'link_type' => LinkItemInterface::LINK_GENERIC,
        ],
    ])
        ->save();
    $entityTypeManager = $this->container
        ->get('entity_type.manager');
    $entityTypeManager->getStorage('entity_form_display')
        ->load('entity_test.entity_test.default')
        ->setComponent($field_name, [
        'type' => 'link_default',
    ])
        ->save();
    $entityTypeManager->getStorage('entity_view_display')
        ->create([
        'targetEntityType' => 'entity_test',
        'bundle' => 'entity_test',
        'mode' => 'full',
        'status' => TRUE,
    ])
        ->setComponent($field_name, [
        'type' => 'link',
    ])
        ->save();
    // Entities can be saved without validation, for example via migration.
    // Link fields may contain invalid uris such as external URLs without
    // scheme.
    $invalidUri = 'www.example.com';
    $invalidLinkUrlEntity = $entityTypeManager->getStorage('entity_test')
        ->create([
        'name' => 'Test entity with invalid link URL',
        $field_name => [
            'uri' => $invalidUri,
        ],
    ]);
    $invalidLinkUrlEntity->save();
    // If a user without 'link to any page' permission edits an entity, widget
    // checks access by converting uri to Url object, which will throw an
    // InvalidArgumentException if uri is invalid.
    $this->drupalLogin($this->drupalCreateUser([
        'view test entity',
        'administer entity_test content',
    ]));
    $this->drupalGet("/entity_test/manage/{$invalidLinkUrlEntity->id()}/edit");
    $this->assertSession()
        ->statusCodeEquals(200);
    $this->assertSession()
        ->fieldValueEquals("{$field_name}[0][uri]", $invalidUri);
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.