function FileFieldWidgetTest::testWidgetValidation

Same name in other branches
  1. 9 core/modules/file/tests/src/Functional/FileFieldWidgetTest.php \Drupal\Tests\file\Functional\FileFieldWidgetTest::testWidgetValidation()
  2. 8.9.x core/modules/file/tests/src/Functional/FileFieldWidgetTest.php \Drupal\Tests\file\Functional\FileFieldWidgetTest::testWidgetValidation()
  3. 10 core/modules/file/tests/src/Functional/FileFieldWidgetTest.php \Drupal\Tests\file\Functional\FileFieldWidgetTest::testWidgetValidation()

Tests validation with the Upload button.

File

core/modules/file/tests/src/Functional/FileFieldWidgetTest.php, line 364

Class

FileFieldWidgetTest
Tests the file field widget with public and private files.

Namespace

Drupal\Tests\file\Functional

Code

public function testWidgetValidation() : void {
    $type_name = 'article';
    $field_name = $this->randomMachineName();
    $this->createFileField($field_name, 'node', $type_name);
    $this->updateFileField($field_name, $type_name, [
        'file_extensions' => 'txt',
    ]);
    $type = 'nojs';
    // Create node and prepare files for upload.
    $node = $this->drupalCreateNode([
        'type' => 'article',
    ]);
    $nid = $node->id();
    $this->drupalGet("node/{$nid}/edit");
    $test_file_text = $this->getTestFile('text');
    $test_file_image = $this->getTestFile('image');
    $name = 'files[' . $field_name . '_0]';
    // Upload file with incorrect extension, check for validation error.
    $edit[$name] = \Drupal::service('file_system')->realpath($test_file_image->getFileUri());
    $this->submitForm($edit, 'Upload');
    $this->assertSession()
        ->pageTextContains("Only files with the following extensions are allowed: txt.");
    // Upload file with correct extension, check that error message is removed.
    $edit[$name] = \Drupal::service('file_system')->realpath($test_file_text->getFileUri());
    $this->submitForm($edit, 'Upload');
    $this->assertSession()
        ->pageTextNotContains("Only files with the following extensions are allowed: txt.");
}

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