What is the correct way to remove an item from a list within hook_entity_view
or hook_preprocess_node
?
I am trying to remove a taxonomy term from a list of terms EntityReferenceFieldItemList
. I calculate two boolean values, if both are true then the item should be removed from the list.
I've tried removing the second item in the list. That works, but removing the first item results in all the items being removed. Is this because the list keys are no longer sequential?
function mymodule_node_view(&$variables) {
# calculate $field_hide_term and $node_in_past
foreach($build['field_terms']['#items'] as $key => $term) {
if ($field_hide_term && $node_in_past) {
unset($build['field_terms'][$key]); # This also removes other items in the list if key is 0.
}
}
}