4

If I do the usual

unset($node->myfilefield["und"][0]);

Would that take care of the actual deletion of the file as well on node_save?

7

No, it doesn't. You should use file_delete(). The function will remove the attached file from the database and from the disk.

// Load the node.
$node = node_load('1');
// Get the language for the file field.
$lang = field_language('node', $node, 'myfilefield');
// load the file
$file = file_load($node->myfilefield[$lang][0]['fid']);
// unset the field for the node
unset($node->myfilefield[$lang][0]);
// delete file from disk and from database
file_delete($file);
// Save the node.
node_save($node);

The file_delete() also takes a second argument $force that if set to TRUE will remove the file even if it's reported as in use by the file_usage table.

10
  • Suppose before saving $node I set $node->revision =1 then in this case will the attachment still be deleted?
    – AgA
    Mar 19 '13 at 7:16
  • @Aga - I guess so, if the file was attached to that revision. But, the best way would be to just try it and see how it works. Mar 20 '13 at 8:19
  • I've tried it and it won't delete it.
    – AgA
    Mar 20 '13 at 12:40
  • @Aga - Was the file attached to an earlier revision? In that case I don't think it would be deleted. I will try it when I get a chance. Mar 21 '13 at 10:18
  • 1
    I figured out the problem was after we unset a value, since it is a multi valued field we must reset the array. hence after resetting we should use '$node->file['und'] = array_values($node->file['und'])'. And it works!
    – ruby
    Sep 12 '14 at 18:10
0

not necessarily call file_delete(), enough:

unset($node->myfilefield["und"][0]);
node_save($node);
3
  • 1
    That will only remove the relation between the file_managed table and your custom image field. It won't remove the file from disk nor will it remove the record in the file_managed table, but thanks for the downvote. Dec 8 '12 at 13:35
  • I checked. File removed from db and filesystem.
    – xandeadx
    Dec 8 '12 at 13:47
  • I tried it and it doesn't work for me. Dec 8 '12 at 14:09

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.