我有相同的用例(想要在保持文件名的同时替换文件),并且自定义模块中的以下代码满足了这一目标。此代码依赖于Entity API模块,因此应作为依赖项添加到模块.info文件中。欢迎反馈。
这允许单击“删除”然后保存节点后立即删除文件。警告:这也意味着当您删除文件并保存节点时,无法通过回滚到较早的修订版本来获取该文件。
/**
* Implements hook_node_update().
*
* Delete files from old node revisions.
*/
function MYMODULE_node_update($node) {
// Array of content types to act on.
if (in_array($node->type, array('page', 'article'))) {
$wrapper = entity_metadata_wrapper('node', $node);
$original_wrapper = entity_metadata_wrapper('node', $node->original);
// Array of file fields to act on.
foreach (array('field_public_files', 'field_private_files') as $field) {
if (!isset($original_wrapper->{$field})) {
continue;
}
$current_files = array();
$original_files = array();
// Get files that were attached to the original node (before update).
foreach ($original_wrapper->{$field}->value() as $file) {
$original_files[] = $file['fid'];
}
// Stop if there were no files previously attached.
if (empty($original_files)) {
continue;
}
// Get files currently attached to the node (after update).
foreach ($wrapper->{$field}->value() as $file) {
$current_files[] = $file['fid'];
}
// Delete files that were in the original node but were removed during
// this update.
$deleted_files = array_diff($original_files, $current_files);
foreach ($deleted_files as $fid) {
if ($file = file_load($fid)) {
// Delete all usages of the file. Each node revision adds to the usage
// count.
file_usage_delete($file, 'file', 'node', $node->nid, 0);
file_delete($file);
}
}
}
}
}