-1

I have multiple images coming dynamically in array. But while adding those images to node only last file get attached in field and other images only saved in file directory. I have tried everything but didn't find any solution. Please help. Please review the code and suggest me the solution.

$node = Node::create(['type' => 'my_contentType']);
$node->set('title', $item['name']);
$node->set('field_author_name', $item['author']);
foreach ($FilePaths_keys as $path){
$digitalFile_path = $item['bitstreams'][$path] ['retrieveLink'];
$get_data_contents = file_get_contents($digitalFile_path);
$file = file_save_data($get_data_contents, 'public://'.$item['bitstreams'][$path]['name'], FILE_EXISTS_REPLACE); 
$Dfiles = [
        'target_id' => $file->id(),
        'alt' => $item['bitstreams'][$path]['name'],
        'title' => $item['bitstreams'][$path]['name']
      ];
$node->set('field_book_image', $Dfiles);
}
$node->enforceIsNew();
$node->save();

Running this code will save all images in directory but only last image got attached with node. How all the images get attach in "field_book_image" unlimited field.

0

Just change your code:

$Dfiles = [];
foreach ($FilePaths_keys as $path){
  ....
  $Dfiles[] = [
        'target_id' => $file->id(),
        'alt' => $item['bitstreams'][$path]['name'],
        'title' => $item['bitstreams'][$path]['name']
      ];
}
$node->set('field_book_image', $Dfiles);
$node->enforceIsNew();
$node->save();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.