How to delete the attachment files programmatically in Drupal(D7 here)?
Somehow I've worked on this code but I'm not sure whether it is fool proof. But at the moment it is working for my site.
In the code field_file_attachment_s_ is the name of attachment field for my site. Assuming there could be multiple files which can be attached to this field. I've yet to test the multiple attachment file deletion feature in the code.
If you've got any better code then I'll be happy to have it.
Thanks for reading this!
$node = node_load($nid); //delete the file field
// Get the language for the file field.
$lang = field_language('node', $node, 'field_file_attachment_s_');
// load the file for ($i = 0; $i < count($node->field_file_attachment_s_[$lang]); ++$i) {
$file = file_load($node->field_file_attachment_s_[$lang][$i]['fid']);
// unset the field for the node
if ($file) {
unset($node->field_file_attachment_s_[$lang][$i]);
// delete file from disk and from database
file_delete($file);
}
}
node_save($node);
No comments:
Post a Comment