You are here

function entityreference_field_formatter_prepare_view in Entity reference 7

Implements hook_field_formatter_prepare_view().

File

./entityreference.module, line 1288
Entityreference primary module file.

Code

function entityreference_field_formatter_prepare_view($entity_type, $entities, $field, $instances, $langcode, &$items, $displays) {
  $field_type_settings = entityreference_field_type_settings($field);
  $target_type = $field_type_settings['entity_type'];
  $column = $field_type_settings['column'];
  $target_ids = array();

  // Collect every possible entity attached to any of the entities.
  foreach ($entities as $id => $entity) {
    foreach ($items[$id] as $delta => $item) {
      if (isset($item[$column])) {
        $target_ids[] = $item[$column];
      }
    }
  }
  if ($target_ids) {
    $target_entities = entity_load($target_type, $target_ids);
  }
  else {
    $target_entities = array();
  }

  // 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[$column]]) && isset($target_entities[$item[$column]])) {

        // Replace the instance value with the term data.
        $items[$id][$delta]['entity'] = $target_entities[$item[$column]];

        // Check whether the user has access to the referenced entity.
        $has_view_access = entity_access('view', $target_type, $target_entities[$item[$column]]) !== FALSE;
        $has_update_access = entity_access('update', $target_type, $target_entities[$item[$column]]) !== FALSE;
        $items[$id][$delta]['access'] = $has_view_access || $has_update_access;
      }
      else {
        unset($items[$id][$delta]);
        $rekey = TRUE;
      }
    }
    if ($rekey) {

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