EntityReferenceFormatterBase.php 2.59 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Contains \Drupal\entity_reference\Plugin\Field\FieldFormatter\EntityReferenceFormatterBase.
6 7
 */

8
namespace Drupal\entity_reference\Plugin\Field\FieldFormatter;
9

10
use Drupal\Core\Field\FormatterBase;
11 12 13 14 15 16 17

/**
 * Parent plugin for entity reference formatters.
 */
abstract class EntityReferenceFormatterBase extends FormatterBase {

  /**
18
   * {@inheritdoc}
19 20 21 22 23
   *
   * Mark the accessible IDs a user can see. We do not unset unaccessible
   * values, as other may want to act on those values, even if they can
   * not be accessed.
   */
24
  public function prepareView(array $entities_items) {
25 26 27 28
    $target_ids = array();
    $revision_ids = array();

    // Collect every possible entity attached to any of the entities.
29 30
    foreach ($entities_items as $items) {
      foreach ($items as $item) {
31 32
        if (!empty($item->revision_id)) {
          $revision_ids[] = $item->revision_id;
33
        }
34 35
        elseif (!empty($item->target_id)) {
          $target_ids[] = $item->target_id;
36 37 38 39
        }
      }
    }

40
    $target_type = $this->getFieldSetting('target_type');
41 42 43 44 45 46 47 48 49 50

    $target_entities = array();

    if ($target_ids) {
      $target_entities = entity_load_multiple($target_type, $target_ids);
    }

    if ($revision_ids) {
      // We need to load the revisions one by-one.
      foreach ($revision_ids as $revision_id) {
51
        $target_entity = entity_revision_load($target_type, $revision_id);
52
        // Use the revision ID in the key.
53 54
        $identifier = $target_entity->id() . ':' . $revision_id;
        $target_entities[$identifier] = $target_entity;
55 56 57 58
      }
    }

    // Iterate through the fieldable entities again to attach the loaded data.
59
    foreach ($entities_items as $items) {
60
      $rekey = FALSE;
61
      foreach ($items as $item) {
62
        // If we have a revision ID, the key uses it as well.
63 64
        $identifier = !empty($item->revision_id) ? $item->target_id . ':' . $item->revision_id : $item->target_id;
        if ($item->target_id !== 0) {
65
          if (!isset($target_entities[$identifier])) {
66 67
            // The entity no longer exists, so empty the item.
            $item->setValue(NULL);
68 69 70 71
            $rekey = TRUE;
            continue;
          }

72
          $item->entity = $target_entities[$identifier];
73

74
          if (!$item->entity->access('view')) {
75 76 77 78
            continue;
          }
        }
        else {
79
          // This is an "auto_create" item, just leave the entity in place.
80 81 82
        }

        // Mark item as accessible.
83
        $item->access = TRUE;
84 85
      }

86
      // Rekey the items array if needed.
87
      if ($rekey) {
88
        $items->filterEmptyValues();
89 90 91
      }
    }
  }
92

93
}