3

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.

2 Answers 2

6

Use unset instead, followed by a save:

unset($wrapper->field_foobar[$delta]);
$wrapper->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) {
    unset($wrapper->field_foobar[$delta]);
    $wrapper->save();
    break;
  }
}
5
  • 1
    I think it'll be target_id for an entity reference field ($field->target_id->value())
    – Clive
    Commented Jan 29, 2015 at 0:32
  • It works! $field->nid->value() is correct. Tyler You saved my day. Thanks.
    – rolkos
    Commented Jan 29, 2015 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. Commented Jan 29, 2015 at 15:31
  • Instead of calling the unset() you may use $wrapper->field_foobar[$delta] = array();
    – mchar
    Commented Jul 18, 2016 at 16:47
  • 1
    Entity metadata wrappers also have the offsetUnset($delta) method. Thus: $wrapper->field_foobar->offsetUnset($delta);
    – htoip
    Commented Mar 1, 2018 at 20:32
0

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);
  });
}

Usage:

$node = node_load(98765);
remove_entity_reference_from_field($node->field_foobar[LANGUAGE_NONE], 12345);
node_save($node);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.