You are here

function ref_field_field_formatter_prepare_view in (Entity)Reference Field Synchronization 7

Implements hook_field_formatter_prepare_view().

File

./ref_field.module, line 343

Code

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

  // Collect every possible entity attached to any of the entities.
  foreach ($entities as $id => $entity) {
    foreach ($items[$id] as $delta => $item) {
      $target_ids[] = $item['eid'];
    }
  }
  if ($target_ids) {
    $target_entities = entity_load($field['settings']['entity'], $target_ids);

    // 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[$item['eid']])) {

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

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