Remove an item from entity reference field

Sign up to bookmark this snippet
Components

Let's say that you have a multivalue reference field named field_tags in a node type. To remove a specific item from that field you can do something like this:

$node_id = 152;
$tag_to_remove = 56;
$entity_storage = \Drupal::entityTypeManager()->getStorage('node');
$entity = $entity_storage->load($node_id);

foreach ($entity->get('field_tags') as $delta => $field_item) {
  if ($field_item->target_id == $tag_to_remove) {
    $entity->get('field_tags')->removeItem($delta);
    $entity->save();
    break;
  }
}