I have a command that imports contents from an external database. I’m able to attach also files with this part of code:
$file = File::create([ 'filename' => $new_filename, 'uri' => $folder_uri . '/' . $new_filename,// private://my_content_type/<subdir>/filename.pdf ]); $file->setPermanent(); $file->save();
and then attach to my new node with this part of code:
$storage_handler = Drupal::entityTypeManager()->getStorage("node"); $data = [ 'type' => 'my_content_type', 'title' => 'A title', 'status' => 1, ... 'field_attach' => ['target_id' => $file->fid->value], ... ]; $node = $storage_handler->create($data); $node->save();
Editing the new content I can correctly find the attached file but opening it in preview I receive "Access Denied", even if I’m the admin. The field field_attach
is a multiple one and manually attaching another file from the edit page, I can correctly preview it.
debug:
This is the devel part for the node:
[field_attach] => Array ( [x-default] => Array ( [0] => Array ( [target_id] => 1876 // Can't preview, access denied [display] => 1 [description] => ) [1] => Array ( [target_id] => 1878 // Can preview it [display] => 1 [description] => ) ) )
In database each file has same values:
# select * from file_usage where fid in(1876, 1878)G *************************** 1. row *************************** fid: 1876 module: file type: node id: 92 count: 1 *************************** 2. row *************************** fid: 1878 module: file type: node id: 92 count: 1 2 rows in set (0.000 sec) # select * from file_managed where fid in(1876, 1878)G *************************** 1. row *************************** fid: 1876 uuid: 876c1bd1-566c-4d6b-a767-4925d75b593f langcode: it uid: 1 filename: first_file.pdf uri: private://my_content_type/201211/first_file.pdf filemime: application/pdf filesize: 140982 status: 1 created: 1651744379 changed: 1651744379 *************************** 2. row *************************** fid: 1878 uuid: 4c26c169-3e92-4254-af49-e5b203caf4c6 langcode: it uid: 1 filename: second_file.pdf uri: private://my_content_type/202205/first_file.pdf filemime: application/pdf filesize: 140982 status: 1 created: 1651745721 changed: 1651745725 2 rows in set (0.000 sec)
Permissions are the same for directories and for files. Something is different from manual and programmatically attach. Lost to set something?
Thanks in advance.