NumberListField.php 2.24 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
<?php

/**
 * @file
 * Contains \Drupal\options\Plugin\views\argument\NumberListField.
 */

namespace Drupal\options\Plugin\views\argument;

use Drupal\Core\Field\AllowedTagsXssTrait;
11
use Drupal\Core\Field\FieldFilteredString;
12
use Drupal\Core\Form\FormStateInterface;
13
use Drupal\views\FieldAPIHandlerTrait;
14 15
use Drupal\views\ViewExecutable;
use Drupal\views\Plugin\views\display\DisplayPluginBase;
16
use Drupal\views\Plugin\views\argument\NumericArgument;
17 18 19 20 21 22 23 24 25

/**
 * Argument handler for list field to show the human readable name in the
 * summary.
 *
 * @ingroup views_argument_handlers
 *
 * @ViewsArgument("number_list_field")
 */
26
class NumberListField extends NumericArgument {
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82

  use AllowedTagsXssTrait;
  use FieldAPIHandlerTrait;

  /**
   * Stores the allowed values of this field.
   *
   * @var array
   */
  protected $allowedValues = NULL;

  /**
   * {@inheritdoc}
   */
  public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
    parent::init($view, $display, $options);

    $field_storage = $this->getFieldStorageDefinition();
    $this->allowedValues = options_allowed_values($field_storage);
  }

  /**
   * {@inheritdoc}
   */
  protected function defineOptions() {
    $options = parent::defineOptions();
    $options['summary']['contains']['human'] = ['default' => FALSE];

    return $options;
  }

  /**
   * {@inheritdoc}
   */
  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
    parent::buildOptionsForm($form, $form_state);

    $form['summary']['human'] = [
      '#title' => $this->t('Display list value as human readable'),
      '#type' => 'checkbox',
      '#default_value' => $this->options['summary']['human'],
      '#states' => [
        'visible' => [
          ':input[name="options[default_action]"]' => ['value' => 'summary'],
        ],
      ],
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function summaryName($data) {
    $value = $data->{$this->name_alias};
    // If the list element has a human readable name show it.
    if (isset($this->allowedValues[$value]) && !empty($this->options['summary']['human'])) {
83
      return FieldFilteredString::create($this->allowedValues[$value]);
84 85 86
    }
    // Else, fallback to the key.
    else {
87
      return $value;
88 89 90 91
    }
  }

}