I have a custom content type with a file field. I am trying to attach a file uploaded through a custom form to the custom content type. I am able to load the node and update all the other values of the node except the file field.
I found Realityloop: Programmatically attach files to a node in Drupal 8, but it doesn't seem to work.
This was what was suggested in the above link
$node = Node::create([ 'type' => 'article', 'title' => 'Druplicon test', 'field_image' => [ 'target_id' => $file->id(), ], ]); $node->save();
This is what I have tried inside
$fid = $form_state->getValue('file_field_name'); $file = File::load($fid); $file->setPermanent(); $file->save(); $node = Node::load($nid); $node->set('file_field_in_node', $file->id); $node->save();
That was setting the file as permanent in the files table but the node did not have the file.
I also tried to save with
That did not help either. I am also curious as to which is the file/function that handles the set function for the file field.
[SOLVED] Not sure what was wrong earlier. Both the approaches seems to be working correctly now. So setting the file_id or the file object into the file field for the node seem to be saving the node correctly with the file attached to it.