How do I programmatically attach a file to a file field in a node? 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' =&gt; 'article',
  'title' =&gt; 'Druplicon test',
  'field_image' =&gt; [
  'target_id' =&gt; $file-&gt;id(),
  ],
]);
$node-&gt;save();


This is what I have tried inside submitForm

$fid = $form_state-&gt;getValue('file_field_name')[0];
$file = File::load($fid);
$file-&gt;setPermanent();
$file-&gt;save();
$node = Node::load($nid);     
$node-&gt;set('file_field_in_node', $file-&gt;id);
$node-&gt;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 

$node-&gt;set('file_field_in_node', $file);


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.

UPDATE:

[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.
In your custom form use code like this:

$form['imagefile'] = [
      '#type' =&gt; 'managed_file',
      '#title' =&gt; $this-&gt;t('Imagefile'),
      '#default_value' =&gt; $this-&gt;configuration['imagefile'],
      '#weight' =&gt; '0',
      '#upload_location' =&gt; 'public://images/redaktion/',
    ];


And here's a piece of code how it works low level:

// check if the folder exists
$folder = date('Y-m', time());
$data = file_get_contents($imagefilepath);
if (!is_dir("/home/rainer/src/asdent/web/sites/default/files/images/pics/{$folder}")) {
      mkdir("/home/rainer/src/asdent/web/sites/default/files/images/pics/{$folder}");
}
// create the file entity
$photo = file_save_data($data, "public://images/pics/{$folder}/".$filename, FILE_EXISTS_REPLACE);

// later in your entity::create:
'myimage' =&gt; ['target_id' =&gt; $photo-&gt;id()],


The trick is to create the file entity beforehand and then link the custom entity to it.