0

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.
    }
  }
}
0

Instead of using unset(), you can use #access = FALSE, like this:

$build['field_terms'][0]['#access'] = FALSE;
| 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.