You are here

function uuidreference_field_formatter_prepare_view in UUID reference field 7

Implements hook_field_formatter_prepare_view().

Ripped directly from entityreference.

File

./uuidreference.module, line 336

Code

function uuidreference_field_formatter_prepare_view($entity_type, $entities, $field, $instances, $langcode, &$items, $displays) {
  $target_uuids = array();

  // Collect every possible entity attached to any of the entities.
  foreach ($entities as $id => $entity) {
    foreach ($items[$id] as $delta => $item) {
      $target_uuids[] = $item['target_uuid'];
    }
  }
  if (!empty($target_uuids)) {

    // This is mostly copied from entity_uuid_load() but that function doesn't
    // return the id map which we will need later.
    $uuid_id_map = entity_get_id_by_uuid($field['settings']['target_type'], $target_uuids);
    $target_entities = entity_load($field['settings']['target_type'], $uuid_id_map);

    // Iterate through the fieldable entities again to attach the loaded data.
    foreach ($entities as $id => $entity) {
      $rekey = FALSE;
      foreach ($items[$id] as $delta => $item) {

        // Check whether the referenced entity could be loaded.
        if (isset($target_entities[$uuid_id_map[$item['target_uuid']]])) {

          // Replace the instance value with the term data.
          $items[$id][$delta]['entity'] = $target_entities[$uuid_id_map[$item['target_uuid']]];
        }
        else {
          unset($items[$id][$delta]);
          $rekey = TRUE;
        }
      }
      if ($rekey) {

        // Rekey the items array.
        $items[$id] = array_values($items[$id]);
      }
    }
  }
}