Version 1
[yaffs-website] / web / core / modules / options / src / Plugin / Field / FieldFormatter / OptionsDefaultFormatter.php
1 <?php
2
3 namespace Drupal\options\Plugin\Field\FieldFormatter;
4
5 use Drupal\Core\Field\AllowedTagsXssTrait;
6 use Drupal\Core\Field\FieldFilteredMarkup;
7 use Drupal\Core\Field\FormatterBase;
8 use Drupal\Core\Field\FieldItemListInterface;
9 use Drupal\Core\Form\OptGroup;
10
11 /**
12  * Plugin implementation of the 'list_default' formatter.
13  *
14  * @FieldFormatter(
15  *   id = "list_default",
16  *   label = @Translation("Default"),
17  *   field_types = {
18  *     "list_integer",
19  *     "list_float",
20  *     "list_string",
21  *   }
22  * )
23  */
24 class OptionsDefaultFormatter extends FormatterBase {
25
26   use AllowedTagsXssTrait;
27
28   /**
29    * {@inheritdoc}
30    */
31   public function viewElements(FieldItemListInterface $items, $langcode) {
32     $elements = [];
33
34     // Only collect allowed options if there are actually items to display.
35     if ($items->count()) {
36       $provider = $items->getFieldDefinition()
37         ->getFieldStorageDefinition()
38         ->getOptionsProvider('value', $items->getEntity());
39       // Flatten the possible options, to support opt groups.
40       $options = OptGroup::flattenOptions($provider->getPossibleOptions());
41
42       foreach ($items as $delta => $item) {
43         $value = $item->value;
44         // If the stored value is in the current set of allowed values, display
45         // the associated label, otherwise just display the raw value.
46         $output = isset($options[$value]) ? $options[$value] : $value;
47         $elements[$delta] = [
48           '#markup' => $output,
49           '#allowed_tags' => FieldFilteredMarkup::allowedTags(),
50         ];
51       }
52     }
53
54     return $elements;
55   }
56
57 }