2 * Implements hook_field_formatter_prepare_view().
4 function {{ machine_name }}_field_formatter_prepare_view($entity_type, $entities, $field, $instances, $langcode, &$items, $displays) {
7 // Collect every possible term attached to any of the fieldable entities.
8 foreach ($entities as $id => $entity) {
9 foreach ($items[$id] as $delta => $item) {
10 // Force the array key to prevent duplicates.
11 $tids[$item['tid']] = $item['tid'];
16 $terms = taxonomy_term_load_multiple($tids);
18 // Iterate through the fieldable entities again to attach the loaded term
20 foreach ($entities as $id => $entity) {
23 foreach ($items[$id] as $delta => $item) {
24 // Check whether the taxonomy term field instance value could be loaded.
25 if (isset($terms[$item['tid']])) {
26 // Replace the instance value with the term data.
27 $items[$id][$delta]['taxonomy_term'] = $terms[$item['tid']];
29 // Otherwise, unset the instance value, since the term does not exist.
31 unset($items[$id][$delta]);
37 // Rekey the items array.
38 $items[$id] = array_values($items[$id]);