TestFieldPrepareViewFormatter.php 2.22 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Contains \Drupal\field_test\Plugin\field\formatter\TestFieldPrepareViewFormatter.
6 7 8 9
 */

namespace Drupal\field_test\Plugin\field\formatter;

10
use Drupal\field\Annotation\FieldFormatter;
11 12 13
use Drupal\Core\Annotation\Translation;
use Drupal\field\Plugin\Type\Formatter\FormatterBase;
use Drupal\Core\Entity\EntityInterface;
14
use Drupal\Core\Entity\Field\FieldInterface;
15 16 17 18

/**
 * Plugin implementation of the 'field_test_with_prepare_view' formatter.
 *
19
 * @FieldFormatter(
20 21 22 23 24 25 26 27 28 29 30 31 32 33
 *   id = "field_test_with_prepare_view",
 *   label = @Translation("With prepare step"),
 *   description = @Translation("Tests prepareView() method"),
 *   field_types = {
 *     "test_field"
 *   },
 *   settings = {
 *     "test_formatter_setting_additional" = "dummy test string"
 *   }
 * )
 */
class TestFieldPrepareViewFormatter extends FormatterBase {

  /**
34
   * {@inheritdoc}
35 36 37 38 39 40 41 42 43 44 45 46 47
   */
  public function settingsForm(array $form, array &$form_state) {
    $element['test_formatter_setting_additional'] = array(
      '#title' => t('Setting'),
      '#type' => 'textfield',
      '#size' => 20,
      '#default_value' => $this->getSetting('test_formatter_setting_additional'),
      '#required' => TRUE,
    );
    return $element;
  }

  /**
48
   * {@inheritdoc}
49 50
   */
  public function settingsSummary() {
51 52 53
    $summary = array();
    $summary[] = t('@setting: @value', array('@setting' => 'test_formatter_setting_additional', '@value' => $this->getSetting('test_formatter_setting_additional')));
    return $summary;
54 55 56
  }

  /**
57
   * {@inheritdoc}
58
   */
59 60 61
  public function prepareView(array $entities, $langcode, array $items) {
    foreach ($entities as $id => $entity) {
      foreach ($items[$id] as $delta => $item) {
62
        // Don't add anything on empty values.
63 64
        if (!$item->isEmpty()) {
          $item->additional_formatter_value = $item->value + 1;
65 66 67 68 69 70
        }
      }
    }
  }

  /**
71
   * {@inheritdoc}
72
   */
73
  public function viewElements(EntityInterface $entity, $langcode, FieldInterface $items) {
74 75 76
    $elements = array();

    foreach ($items as $delta => $item) {
77
      $elements[$delta] = array('#markup' => $this->getSetting('test_formatter_setting_additional') . '|' . $item->value . '|' . $item->additional_formatter_value);
78 79 80 81 82
    }

    return $elements;
  }
}