function dynamic_entity_reference_field_formatter_prepare_view in Dynamic Entity Reference 7
Implements hook_field_formatter_prepare_view().
File
- ./
dynamic_entity_reference.field.inc, line 252 - Contains field hooks.
Code
function dynamic_entity_reference_field_formatter_prepare_view($entity_type, $entities, $field, $instances, $langcode, &$entity_items, $displays) {
if ($field['type'] == 'dynamic_entity_reference') {
$target_ids = array();
$revision_ids = array();
foreach ($entity_items as $items) {
// Collect every possible entity attached to any of the entities.
foreach ($items as $item) {
if (!empty($item['revision_id']) && !empty($item['target_type'])) {
$revision_ids[$item['target_type']][] = $item['revision_id'];
}
elseif (!empty($item['target_id']) && !empty($item['target_type'])) {
$target_ids[$item['target_type']][] = $item['target_id'];
}
}
}
$target_entities = array();
if ($target_ids) {
foreach ($target_ids as $target_type => $ids) {
$target_entities_for_type = entity_load($target_type, $ids);
foreach ($target_entities_for_type as $id => $target_entity) {
$target_entities[$target_type][$id] = entity_metadata_wrapper($target_type, $target_entity);
}
}
}
if ($revision_ids) {
// We need to load the revisions one by-one.
foreach ($revision_ids as $target_type => $rev_ids) {
foreach ($rev_ids as $revision_id) {
$target_entity = entity_revision_load($target_type, $revision_id);
$target_entity_wrapper = entity_metadata_wrapper($target_type, $target_entity);
// Use the revision ID in the key.
$identifier = $target_entity_wrapper
->getIdentifier() . ':' . $revision_id;
$target_entities[$target_type][$identifier] = $target_entity_wrapper;
}
}
}
// Iterate through the fieldable entities again to attach the loaded data.
$rekey = FALSE;
foreach ($entity_items as $key => $items) {
foreach ($items as $delta => $item) {
// If we have a revision ID, the key uses it as well.
$identifier = !empty($item['revision_id']) ? $item['target_id'] . ':' . $item['revision_id'] : $item['target_id'];
if ($item['target_id'] !== 0) {
if (!isset($item['target_type']) || !isset($target_entities[$item['target_type']][$identifier])) {
// The entity no longer exists, so empty the item.
unset($items[$delta]);
$rekey = TRUE;
continue;
}
$item['entity'] = $target_entities[$item['target_type']][$identifier];
if (!entity_access('view', $item['target_type'], $item['entity']
->value())) {
continue;
}
}
else {
// This is an "auto_create" item, just leave the entity in place.
}
// Mark item as accessible.
$item['access'] = TRUE;
$items[$delta] = $item;
}
// Rekey the items array if needed.
if ($rekey) {
$items = array_values(array_filter($items, function ($item) {
return isset($item) && isset($item['entity']) && !empty($item['access']);
}));
}
$entity_items[$key] = $items;
}
}
}