function FileFieldWidgetTest::testSingleValuedWidget

Tests upload and remove buttons for a single-valued File field.

File

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

Class

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

Namespace

Drupal\Tests\file\Functional

Code

public function testSingleValuedWidget() {
  $node_storage = $this->container
    ->get('entity_type.manager')
    ->getStorage('node');
  $type_name = 'article';
  $field_name = strtolower($this->randomMachineName());
  $this->createFileField($field_name, 'node', $type_name);
  $test_file = $this->getTestFile('text');
  // Create a new node with the uploaded file and ensure it got uploaded
  // successfully.
  $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
  $node = $node_storage->loadUnchanged($nid);
  $node_file = File::load($node->{$field_name}->target_id);
  $this->assertFileExists($node_file->getFileUri());
  // Ensure the file can be downloaded.
  $this->drupalGet($node_file->createFileUrl());
  $this->assertSession()
    ->statusCodeEquals(200);
  // Ensure the edit page has a remove button instead of an upload button.
  $this->drupalGet("node/{$nid}/edit");
  $this->assertNoFieldByXPath('//input[@type="submit"]', t('Upload'), 'Node with file does not display the "Upload" button.');
  $this->assertFieldByXpath('//input[@type="submit"]', t('Remove'), 'Node with file displays the "Remove" button.');
  $this->drupalPostForm(NULL, [], t('Remove'));
  // Ensure the page now has an upload button instead of a remove button.
  $this->assertNoFieldByXPath('//input[@type="submit"]', t('Remove'), 'After clicking the "Remove" button, it is no longer displayed.');
  $this->assertFieldByXpath('//input[@type="submit"]', t('Upload'), 'After clicking the "Remove" button, the "Upload" button is displayed.');
  // Test label has correct 'for' attribute.
  $input = $this->xpath('//input[@name="files[' . $field_name . '_0]"]');
  $label = $this->xpath('//label[@for="' . $input[0]->getAttribute('id') . '"]');
  $this->assertTrue(isset($label[0]), 'Label for upload found.');
  // Save the node and ensure it does not have the file.
  $this->drupalPostForm(NULL, [], t('Save'));
  $node = $node_storage->loadUnchanged($nid);
  $this->assertTrue(empty($node->{$field_name}->target_id), 'File was successfully removed from the node.');
}

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