I have some D8 entity code that does read-modify-write on a multivalue entity-reference field. The modification required is to change references to one entity to refer to another, without changing other references.
I get an exception thrown in $entity->set(...)
saying that the Value is not an entity. I presume I'm calling the wrong thin somewhere but I don't see what the correct call pattern would be.
What I have at present is, and here $field_values is a EntityReferenceFieldItemList:
$field = '...';
$entity = $storage->load(...);
$field_values = $entity->{$field};
foreach ($field_values as $k => &$item) {
$target_id = $item->get('target_id')->getValue();
if ($target_id === $old_value->id()) {
$changed = TRUE;
$item->set('target_id', $new_value);
}
}
if ($changed) {
var_dump($field_values);
$entity->set($field, $field_values);
$entity->save();
}
where $old_value and $new_value are both EntityInterface objects and $field_values is an EntityReferenceFieldItemList.