I have a entity reference field that holds relations to multiple nodes. I have to remove one item programmatically based on nid. Normally to remove item I've just set it to null like this:

$wrapper->field_foobar = NULL;

But entity reference is a list, so I have to know delta for element to do something like this:

$wrapper->field_foobar[$delta] = NULL;

So I have content_id and target_id what should I do to find delta? I know it's possible to do it with simple SQL query, but I gues there should be some way to do that with entity metadata .

Any sugestions?

I'm on Drupal 7 of course.


Use unset instead, followed by a save:


To find the delta, you can iterate over the collection and look for the node id:

foreach($wrapper->field_foobar as $delta => $item)  {
  if ($item->nid->value() == $my_id) {
|improve this answer|||||
  • 1
    I think it'll be target_id for an entity reference field ($field->target_id->value()) – Clive Jan 29 '15 at 0:32
  • It works! $field->nid->value() is correct. Tyler You saved my day. Thanks. – rolkos Jan 29 '15 at 11:52
  • Thank you for clarifying. In summary, when iterating over an entity reference field on a wrapped object, each iteration's object will also be a fully wrapped entity. – tyler.frankenstein Jan 29 '15 at 15:31
  • Instead of calling the unset() you may use $wrapper->field_foobar[$delta] = array(); – mchar Jul 18 '16 at 16:47
  • 1
    Entity metadata wrappers also have the offsetUnset($delta) method. Thus: $wrapper->field_foobar->offsetUnset($delta); – htoip Mar 1 '18 at 20:32

You could create a function for it, like this:

function remove_entity_reference_from_field(&$field, $reference_id){
  $field = array_filter($field, function($value) use ($reference_id) {
    return ($value['target_id'] != $entity_id);


$node = node_load(98765);
remove_entity_reference_from_field($node->field_foobar[LANGUAGE_NONE], 12345);
|improve this answer|||||

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.