How do I attach a file to a file field when saving (update/insert) a node? After creating programmatically a PDF file with TCPDF, I am trying to attach it to my field "file_fichier", here is what my code looks like

/**
 * Implements hook_node_presave().
 */
function hook_node_presave($node) {

  if($node-&gt;type=='profil'){

    $uri = 'public://profiles/fichier';
    $filename = $node-&gt;title.' - PDF - '.$node-&gt;language.'.pdf';
    $file_path = $uri . '/' . $filename;

    // Output PDF with TCPDF
    $pdf-&gt;Output($file_path, 'F');

    $file = new stdClass;
    $file-&gt;uid = $node-&gt;uid;
    $file-&gt;filename = pathinfo($file_path, PATHINFO_BASENAME);
    $file-&gt;uri = $file_path;
    $file-&gt;filemime = file_get_mimetype($file_path);
    $file-&gt;status = FILE_STATUS_PERMANENT;
    file_save($file);

    dpm($file);

    // Now attach file to the file field.
    $node-&gt;field_fichier[$node-&gt;language][] = (array) $file;

  }

}


The PDF file is well saved to public://profiles/fichier/file_name.pdf as expected, and it's also recorded to the 'file_managed' table. 

But the problem is that it's not attached to the field field_fichier, and nothing seems to happen to the field_data_field_fichier table
I think that you don't have the fid.

/**
 * Implements hook_node_presave().
 */
function hook_node_presave($node) {

  if($node-&gt;type=='profil'){

    $uri = 'public://profiles/fichier';
    $filename = $node-&gt;title.' - PDF - '.$node-&gt;language.'.pdf';
    $file_path = $uri . '/' . $filename;

    // Output PDF with TCPDF
    $pdf-&gt;Output($file_path, 'F');

    $file_temp = file_get_contents($file_path);

    // Saves a file to the specified destination and creates a database entry.
    $file_temp = file_save_data($file_temp, $file_path, FILE_EXISTS_RENAME);

   $node-&gt;field_fichier = array(
     'und' =&gt; array(
       0 =&gt; array(
        'fid' =&gt; $file_temp-&gt;fid,
        'filename' =&gt; $file_temp-&gt;filename,
        'filemime' =&gt; $file_temp-&gt;filemime,
        'uid' =&gt; $node-&gt;uid;,
        'uri' =&gt; $file_temp-&gt;uri,
        'status' =&gt; 1,
        'display' =&gt; 1
    )
  )
);