Version 1
[yaffs-website] / web / core / modules / options / src / Plugin / views / argument / NumberListField.php
1 <?php
2
3 namespace Drupal\options\Plugin\views\argument;
4
5 use Drupal\Core\Field\AllowedTagsXssTrait;
6 use Drupal\Core\Field\FieldFilteredMarkup;
7 use Drupal\Core\Form\FormStateInterface;
8 use Drupal\views\FieldAPIHandlerTrait;
9 use Drupal\views\ViewExecutable;
10 use Drupal\views\Plugin\views\display\DisplayPluginBase;
11 use Drupal\views\Plugin\views\argument\NumericArgument;
12
13 /**
14  * Argument handler for list field to show the human readable name in the
15  * summary.
16  *
17  * @ingroup views_argument_handlers
18  *
19  * @ViewsArgument("number_list_field")
20  */
21 class NumberListField extends NumericArgument {
22
23   use AllowedTagsXssTrait;
24   use FieldAPIHandlerTrait;
25
26   /**
27    * Stores the allowed values of this field.
28    *
29    * @var array
30    */
31   protected $allowedValues = NULL;
32
33   /**
34    * {@inheritdoc}
35    */
36   public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
37     parent::init($view, $display, $options);
38
39     $field_storage = $this->getFieldStorageDefinition();
40     $this->allowedValues = options_allowed_values($field_storage);
41   }
42
43   /**
44    * {@inheritdoc}
45    */
46   protected function defineOptions() {
47     $options = parent::defineOptions();
48     $options['summary']['contains']['human'] = ['default' => FALSE];
49
50     return $options;
51   }
52
53   /**
54    * {@inheritdoc}
55    */
56   public function buildOptionsForm(&$form, FormStateInterface $form_state) {
57     parent::buildOptionsForm($form, $form_state);
58
59     $form['summary']['human'] = [
60       '#title' => $this->t('Display list value as human readable'),
61       '#type' => 'checkbox',
62       '#default_value' => $this->options['summary']['human'],
63       '#states' => [
64         'visible' => [
65           ':input[name="options[default_action]"]' => ['value' => 'summary'],
66         ],
67       ],
68     ];
69   }
70
71   /**
72    * {@inheritdoc}
73    */
74   public function summaryName($data) {
75     $value = $data->{$this->name_alias};
76     // If the list element has a human readable name show it.
77     if (isset($this->allowedValues[$value]) && !empty($this->options['summary']['human'])) {
78       return FieldFilteredMarkup::create($this->allowedValues[$value]);
79     }
80     // Else, fallback to the key.
81     else {
82       return $value;
83     }
84   }
85
86 }