I have a setup with views PDF which send email after creating a node. (This works)
For logging purpose I would like the PDF added to my node in a filefield.
Is there a rule action/php code available to add the saved PDF to the filefield.
2 Answers
For adding/attaching a file to a node using code you need a file object. If you know the path of the created PDF file, just try the following code in the hook you need. I used this code in hook_node_insert for attaching a programmatically created PDF file, while creating that node.
$source_node = node_load($nid); //load your required node here.
$file_path = 'your file path';
$file = new stdClass;
$file->uid = $source_node->uid;
$file->filename = $filename; //your file name;
$file->uri = $file_path;
$file->filemime = file_get_mimetype($file_path);
// Make it permanent, otherwise it will get deleted later.
$file->status = FILE_STATUS_PERMANENT;
// Save file object to make it a 'managed file'.
$file_obj = file_copy($file, 'new path for your file', FILE_EXISTS_REPLACE);
$source_node->your_file_field_name['und'][0] = array(
'fid' => $file_obj->fid,
'uid' => $file_obj->uid,
'filename' => $file_obj->filename,
'uri' => $file_obj->uri,
'filemime' => $file_obj->filemime,
'filesize' => $file_obj->filesize,
'status' => 1,
'display' => 1,
'description' => '',
);
node_save($source_node);
Hope this will help you.
-
copy the file works. but i still get error: EntityMalformedException: Missing bundle property on entity of type node. in entity_extract_ids() (rule 7879 van /includes/common.inc). @Abin– pindamanCommented Dec 23, 2015 at 14:41
-
$nid = $node->nid;
$source_node = node_load($nid);
$filename = 'filename.pdf'; //your specific filename
$dir = 'public://'.$filename; //path to specific file with name
$file_size = filesize($dir);
$source_node->type = 'my_nodetype'; // error if not used
//New file object
$file = new stdClass;
$file->uid = $source_node->uid;
$file->filename = $filename; //your file name;
$file->uri = $dir;
$file->filemime = file_get_mimetype($dir);
// Make it permanent, otherwise it will get deleted later.
$file->status = FILE_STATUS_PERMANENT;
// Save file object to make it a 'managed file'.
$file_obj = file_copy($file, 'public://', FILE_EXISTS_REPLACE);
$file->type = 'document';
$source_node->field_custom_name['und'][0] = array(
'fid' => $file_obj->fid,
'uid' => $file_obj->uid,
'filename' => $file_obj->filename,
'uri' => $file_obj->uri,
'filemime' => $file_obj->filemime,
'filesize' => $file_obj->filesize,
'status' => 1,
'display' => 1,
'description' => '',
);
node_save($source_node);
file_usage_add($file_obj, 'file', 'node', $source_node->nid);
PDF is attached to current node. thanks for help. Is anypone has the code to do the same with entitywrapper. please share.