You are here

function FileFieldTestBase::uploadNodeFiles in Zircon Profile 8.0

Same name and namespace in other branches
  1. 8 core/modules/file/src/Tests/FileFieldTestBase.php \Drupal\file\Tests\FileFieldTestBase::uploadNodeFiles()

Uploads multiple files to a node.

Parameters

\Drupal\file\FileInterface[] $files: The files to be uploaded.

string $field_name: The name of the field on which the files should be saved.

$nid_or_type: A numeric node id to upload files to an existing node, or a string indicating the desired bundle for a new node.

bool $new_revision: The revision number.

array $extras: Additional values when a new node is created.

Return value

int The node id.

2 calls to FileFieldTestBase::uploadNodeFiles()
FileFieldTestBase::uploadNodeFile in core/modules/file/src/Tests/FileFieldTestBase.php
Uploads a file to a node.
FileFieldWidgetTest::testMultiValuedWidget in core/modules/file/src/Tests/FileFieldWidgetTest.php
Tests upload and remove buttons for multiple multi-valued File fields.

File

core/modules/file/src/Tests/FileFieldTestBase.php, line 188
Contains \Drupal\file\Tests\FileFieldTestBase.

Class

FileFieldTestBase
Provides methods specifically for testing File module's field handling.

Namespace

Drupal\file\Tests

Code

function uploadNodeFiles(array $files, $field_name, $nid_or_type, $new_revision = TRUE, array $extras = array()) {
  $edit = array(
    'title[0][value]' => $this
      ->randomMachineName(),
    'revision' => (string) (int) $new_revision,
  );
  $node_storage = $this->container
    ->get('entity.manager')
    ->getStorage('node');
  if (is_numeric($nid_or_type)) {
    $nid = $nid_or_type;
    $node_storage
      ->resetCache(array(
      $nid,
    ));
    $node = $node_storage
      ->load($nid);
  }
  else {

    // Add a new node.
    $extras['type'] = $nid_or_type;
    $node = $this
      ->drupalCreateNode($extras);
    $nid = $node
      ->id();

    // Save at least one revision to better simulate a real site.
    $node
      ->setNewRevision();
    $node
      ->save();
    $node_storage
      ->resetCache(array(
      $nid,
    ));
    $node = $node_storage
      ->load($nid);
    $this
      ->assertNotEqual($nid, $node
      ->getRevisionId(), 'Node revision exists.');
  }

  // Attach files to the node.
  $field_storage = FieldStorageConfig::loadByName('node', $field_name);

  // File input name depends on number of files already uploaded.
  $field_num = count($node->{$field_name});
  $name = 'files[' . $field_name . "_{$field_num}]";
  if ($field_storage
    ->getCardinality() != 1) {
    $name .= '[]';
  }
  foreach ($files as $file) {
    $file_path = $this->container
      ->get('file_system')
      ->realpath($file
      ->getFileUri());
    if (count($files) == 1) {
      $edit[$name] = $file_path;
    }
    else {
      $edit[$name][] = $file_path;
    }
  }
  $this
    ->drupalPostForm("node/{$nid}/edit", $edit, t('Save and keep published'));
  return $nid;
}