public function MinisiteTestBase::uploadNodeFiles in Mini site 8
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.
int|string $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.
1 call to MinisiteTestBase::uploadNodeFiles()
- MinisiteTestBase::uploadNodeFile in tests/
src/ Functional/ MinisiteTestBase.php - Uploads a file to a node.
File
- tests/
src/ Functional/ MinisiteTestBase.php, line 177
Class
- MinisiteTestBase
- Provides methods specifically for testing Minisite module's field handling.
Namespace
Drupal\Tests\minisite\FunctionalCode
public function uploadNodeFiles(array $files, $field_name, $nid_or_type, $new_revision = TRUE, array $extras = []) {
$edit = [
'title[0][value]' => $this
->randomMachineName(),
'revision' => (string) (int) $new_revision,
];
$node_storage = $this->container
->get('entity_type.manager')
->getStorage('node');
if (is_numeric($nid_or_type)) {
$nid = $nid_or_type;
$node_storage
->resetCache([
$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([
$nid,
]);
$node = $node_storage
->load($nid);
$this
->assertNotEqual($nid, $node
->getRevisionId(), 'Node revision exists.');
}
$this
->drupalGet("node/{$nid}/edit");
$page = $this
->getSession()
->getPage();
// 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});
foreach ($files as $i => $file) {
$delta = $field_num + $i;
$file_path = $this->container
->get('file_system')
->realpath($file
->getFileUri());
$name = 'files[' . $field_name . '_' . $delta . ']';
if ($field_storage
->getCardinality() != 1) {
$name .= '[]';
}
if (count($files) == 1) {
$edit[$name] = $file_path;
}
else {
$page
->attachFileToField($name, $file_path);
$this
->drupalPostForm(NULL, [], $this
->t('Upload'));
}
}
$this
->drupalPostForm(NULL, $edit, $this
->t('Save'));
return $nid;
}