How to clear image (or file) field data for specific node programmatically?
Solution
I assume that your field accepts only one file at a time. This is the code you need to use:
// Replace this with the ID of the node you want to update.
$node_id = 123;
/** @var \Drupal\node\NodeInterface $node */
$node = \Drupal\node\Entity\Node::load($node_id);
// Step 1: remove the file. This will actually delete the file from the
// filesystem, so in case you want to keep it just remove the next two
// lines.
/** @var \Drupal\file\FileInterface $file */
$file = $node->get('field_NAME_OF_YOUR_FIELD')->entity;
$file->delete();
// Step 2: remove the field data.
// The 0 in this case is the index of the item you want to remove. It simply
// means the first value in that field needs to be removed.
$node->get('field_NAME_OF_YOUR_FIELD')->removeItem(0);
// We have to save the changes to the node.
$node->save();
OTHER TIPS
Just to offer an alternate solution
$nid = 123;
// Load the node (EDIT:) while checking if it exists
if(!$node = \Drupal::service('entity_type.manager')
->getStorage('node')
->load($nid)) {
// No results for the $nid, bail out early
return;
}
// EDIT: To make sure there's a value on the field
if(!$node->hasField('field_name') || $node->get('field_name')->isEmpty(){
return;
}
// Grab the file entity and make it temporary.
// Deletion will be handled by cron.
$file = $node->get('field_name')
->entity
->set('status', 0)
->save();
// Unset the value on the file ref field and save
$node->set('field_name', '')
->save()
A solution for multiple files (also good for avoiding errors when the field is empty):
$nid = 123;
$node = \Drupal\node\Entity\Node::load($nid);
// Grab the file entities and make them temporary.
// Deletion should be handled by cron.
$items = $node->get('field_NAME_OF_YOUR_FIELD');
foreach ($items as $item) {
$file = $item->entity;
$file->set('status', 0);
$file->save();
}
// Unset the values on the file ref field and save
$node->set('field_NAME_OF_YOUR_FIELD', []);
$node->save();
This code is based on @Mrweiner great answer.
Licensed under: CC-BY-SA with attribution
Not affiliated with drupal.stackexchange