You are here

function entityreference_multiple_field_formatter_prepare_view in Entity reference multiple display 7

Implements hook_field_formatter_prepare_view(). Code duplicate from entityreference.module to load entity for view.

File

./entityreference_multiple.module, line 175
Extend entity reference formatter with an option to separate elements display with specific view_modes.

Code

function entityreference_multiple_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) {
    if (isset($displays[$id]['type']) && $displays[$id]['type'] == 'entityreference_entity_multiple_view') {
      foreach ($items[$id] as $delta => $item) {
        if (isset($item['target_id'])) {
          $target_ids[] = $item['target_id'];
        }
      }
    }
  }
  if ($target_ids) {
    $target_entities = entity_load($field['settings']['target_type'], $target_ids);
  }
  else {
    $target_entities = array();
  }

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

        // Check whether the referenced entity could be loaded and that the user has access to it.
        if (isset($target_entities[$item['target_id']]) && entity_access('view', $field['settings']['target_type'], $target_entities[$item['target_id']])) {

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

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