1 entityreference.module entityreference_field_formatter_prepare_view($entity_type, $entities, $field, $instances, $langcode, &$items, $displays)

Implements hook_field_formatter_prepare_view().

File

core/modules/entityreference/entityreference.module, line 1255
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];
      }
    }
  }

  $target_entities = array();
  if ($target_ids) {
    if (entity_get_info($target_type)) {
      $target_entities = entity_load_multiple($target_type, $target_ids);
    }
    else {
      watchdog(
      'entityreference', 
      'The field %field_label references entities of type %entity_type, but that entity type does not exist.', 
      array(
        '%field_label' => $field['field_name'],
        '%entity_type' => $target_type,
      ), 
      WATCHDOG_ERROR
      );
    }
  }

  // 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]])) {
        // 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);
      }
      // Otherwise, unset the instance value, since the entity does not exist.
      else {
        unset($items[$id][$delta]);
        $rekey = TRUE;
      }
    }

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