taxonomy_field_formatter_prepare_view

Versions
7
taxonomy_field_formatter_prepare_view($obj_type, $objects, $field, $instances, $langcode, &$items, $displays)

Implements hook_field_formatter_prepare_view().

This preloads all taxonomy terms for multiple loaded objects at once and unsets values for invalid terms that do not exist.

Code

modules/taxonomy/taxonomy.module, line 1147

<?php
function taxonomy_field_formatter_prepare_view($obj_type, $objects, $field, $instances, $langcode, &$items, $displays) {
  $tids = array();

  // Collect every possible term attached to any of the fieldable entities.
  foreach ($objects as $id => $object) {
    foreach ($items[$id] as $delta => $item) {
      // Force the array key to prevent duplicates.
      $tids[$item['tid']] = $item['tid'];
    }
  }
  if ($tids) {
    $terms = taxonomy_term_load_multiple($tids);

    // Iterate through the fieldable entities again to attach the loaded term data.
    foreach ($objects as $id => $object) {
      foreach ($items[$id] as $delta => $item) {
        // Check whether the taxonomy term field instance value could be loaded.
        if (isset($terms[$item['tid']])) {
          // Replace the instance value with the term data.
          $items[$id][$delta]['taxonomy_term'] = $terms[$item['tid']];
        }
        // Otherwise, unset the instance value, since the term does not exist.
        else {
          unset($items[$id][$delta]);
        }
      }
    }
  }
}
?>
Login or register to post comments
 
 

All source code and documentation on this site is released under the terms of the GNU General Public License, version 2 and later. Drupal is a registered trademark of Dries Buytaert.