TaxonomyFormatterBase.php 1.91 KB
Newer Older
1 2 3 4 5 6 7
<?php

/**
 * @file
 * Contains \Drupal\taxonomy\Plugin\field\formatter\TaxonomyFormatterBase.
 */

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

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

/**
 * Base class for the taxonomy_term formatters.
 */
abstract class TaxonomyFormatterBase extends FormatterBase {

  /**
18
   * {@inheritdoc}
19 20 21 22
   *
   * This preloads all taxonomy terms for multiple loaded objects at once and
   * unsets values for invalid terms that do not exist.
   */
23
  public function prepareView(array $entities_items) {
24 25 26
    $tids = array();

    // Collect every possible term attached to any of the fieldable entities.
27 28
    foreach ($entities_items as $items) {
      foreach ($items as $item) {
29
        // Force the array key to prevent duplicates.
30
        if ($item->target_id != NULL) {
31
          $tids[$item->target_id] = $item->target_id;
32 33 34 35
        }
      }
    }
    if ($tids) {
36
      $terms = entity_load_multiple('taxonomy_term', $tids);
37 38 39

      // Iterate through the fieldable entities again to attach the loaded term
      // data.
40
      foreach ($entities_items as $items) {
41 42
        $rekey = FALSE;

43
        foreach ($items as $item) {
44 45
          // Check whether the taxonomy term field instance value could be
          // loaded.
46
          if (isset($terms[$item->target_id])) {
47
            // Replace the instance value with the term data.
48
            $item->entity = $terms[$item->target_id];
49 50
          }
          // Terms to be created are not in $terms, but are still legitimate.
51
          elseif ($item->target_id === NULL && isset($item->entity)) {
52 53 54 55
            // Leave the item in place.
          }
          // Otherwise, unset the instance value, since the term does not exist.
          else {
56
            $item->setValue(NULL);
57 58 59 60
            $rekey = TRUE;
          }
        }

61
        // Rekey the items array if needed.
62
        if ($rekey) {
63
          $items->filterEmptyItems();
64 65 66 67 68 69
        }
      }
    }
  }

}