TaxonomyFormatterBase.php 2.15 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
<?php

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

namespace Drupal\taxonomy\Plugin\field\formatter;

use Drupal\Component\Annotation\Plugin;
use Drupal\Core\Annotation\Translation;
use Drupal\Core\Entity\EntityInterface;
use Drupal\field\Plugin\Type\Formatter\FormatterBase;

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

  /**
   * Implements \Drupal\field\Plugin\Type\Formatter\FormatterInterface::prepareView().
   *
   * This preloads all taxonomy terms for multiple loaded objects at once and
   * unsets values for invalid terms that do not exist.
   */
  public function prepareView(array $entities, $langcode, array &$items) {
    $tids = array();

    // Collect every possible term attached to any of the fieldable entities.
    foreach ($entities as $id => $entity) {
      foreach ($items[$id] as $delta => $item) {
        // Force the array key to prevent duplicates.
33
        if ($item['tid'] !== 0) {
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
          $tids[$item['tid']] = $item['tid'];
        }
      }
    }
    if ($tids) {
      $terms = taxonomy_term_load_multiple($tids);

      // Iterate through the fieldable entities again to attach the loaded term
      // data.
      foreach ($entities as $id => $entity) {
        $rekey = FALSE;

        foreach ($items[$id] as $delta => $item) {
          // Check whether the taxonomy term field instance value could be
          // loaded.
          if (isset($terms[$item['tid']])) {
            // Replace the instance value with the term data.
            $items[$id][$delta]['entity'] = $terms[$item['tid']];
          }
          // Terms to be created are not in $terms, but are still legitimate.
54
          elseif ($item['tid'] === 0 && isset($item['entity'])) {
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
            // Leave the item in place.
          }
          // Otherwise, unset the instance value, since the term does not exist.
          else {
            unset($items[$id][$delta]);
            $rekey = TRUE;
          }
        }

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

}