I have a custom script that imports contents from an external database.
I'm attaching files using the below custom code.
$file = File::create([
'filename' => $new_filename,
'uri' => $folder_uri . '/' . $new_filename,// private://my_content_type/<subdir>/filename.pdf
]);
$file->setPermanent();
$file->save();
Once the above part is complete, then attach that file(s) to the new node using the below custom 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();
When I edit the same node I see the correct file attached but while opening it in preview, I receive "Access Denied", even I'm logged as an admin.
Though, the field field_attach
is a multiple one and if I manually attach another file from the edit page and save it, then 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.