How do I programmatically delete a reference field value? I have a multi-valued taxonomy reference field named field_classrooms in a node type. I use below code to delete the value in the field.

$node = Drupal\node\Entity\Node::load('1512');
unset($node-&gt;field_classrooms[0]);
$node-&gt;save();


I can't figure out what I am doing wrong here.
Maybe something like this could help you out

// Get the list of the associated classrooms ...
$classrooms = $node-&gt;get('field_classrooms')-&gt;getValue();
// ... if there are any associated classrooms ...
if(!empty($classrooms)) {
  foreach($classrooms as $classroom) {
    // ... get the key of the classroom
    $key = array_search(current($classroom), array_column($classrooms, key($classroom)));
    // ... remove the relationship ...
    $node-&gt;get('field_classrooms')-&gt;removeItem($key);
  }
  // ... and save the node.
  $node-&gt;save();
}


If you want to remove a single classroom from the list and you already know the tid

private function removeClassroomFromNode($node, $tid) {
  if(null != $node) {
    // ... get the list of associated classrooms
    $classrooms = $node-&gt;get('field_classrooms')-&gt;getValue();
    // ... get the key of the classroom
    $key = array_search($tid, array_column($classrooms, 'target_id'));
    // ... remove the classroom
    $node-&gt;get('field_classrooms')-&gt;removeItem($key);
    // ... save the node.
    $node-&gt;save();
  }
}