1

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->type=='profil'){

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

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

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

    dpm($file);

    // Now attach file to the file field.
    $node->field_fichier[$node->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

  • do you solve your problem? – Adrian Cid Almaguer Aug 22 '16 at 15:59
  • @AdrianCidAlmaguer, I finally avoided to link the pdf with my node field. I simply saved it during node add/edit process into a specific directory. Then I loaded it directly into theme file. I checked your solution but didn't find the time to test it. I think my $file object had already an fid after file_save() was triggered. – 118218 Aug 23 '16 at 6:54
  • If you post your solution is better for other users that can have in the future the same problem, and you can check your answer as accepted. – Adrian Cid Almaguer Aug 23 '16 at 14:19
1

I think that you don't have the fid.

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

  if($node->type=='profil'){

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

    // Output PDF with TCPDF
    $pdf->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->field_fichier = array(
     'und' => array(
       0 => array(
        'fid' => $file_temp->fid,
        'filename' => $file_temp->filename,
        'filemime' => $file_temp->filemime,
        'uid' => $node->uid;,
        'uri' => $file_temp->uri,
        'status' => 1,
        'display' => 1
    )
  )
);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.