You are here

SelectOtherFormatter.php in CCK Select Other 8

File

src/Plugin/Field/FieldFormatter/SelectOtherFormatter.php
View source
<?php

namespace Drupal\cck_select_other\Plugin\Field\FieldFormatter;

use Drupal\Core\Field\FieldFilteredMarkup;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Field\FieldItemListInterface;

/**
 * Plugin implementation of the 'cck_select_other' formatter.
 *
 * @FieldFormatter(
 *   id = "cck_select_other",
 *   label = @Translation("Default"),
 *   field_types = {
 *     "list_integer",
 *     "list_float",
 *     "list_string",
 *   }
 * )
 */
class SelectOtherFormatter extends FormatterBase {

  /**
   * {@inheritdoc}
   */
  public function viewElements(FieldItemListInterface $items, $langcode) {
    $elements = [];
    $allowed_values = $this
      ->getFieldSetting('allowed_values');
    foreach ($items as $delta => $item) {
      if (isset($allowed_values[$item->value])) {
        $output = FieldFilteredMarkup::create($allowed_values[$item->value]);
      }
      else {

        // If no match was found in allowed values, fall back to the key.
        $output = FieldFilteredMarkup::create($item->value);
      }
      $elements[$delta] = [
        '#markup' => $output,
      ];
    }
    return $elements;
  }

}

Classes

Namesort descending Description
SelectOtherFormatter Plugin implementation of the 'cck_select_other' formatter.