Version 1
[yaffs-website] / web / core / modules / views / src / Plugin / views / field / MachineName.php
1 <?php
2
3 namespace Drupal\views\Plugin\views\field;
4
5 use Drupal\Core\Form\FormStateInterface;
6 use Drupal\views\ResultRow;
7
8 /**
9  * Field handler which allows to show machine name content as human name.
10  * @ingroup views_field_handlers
11  *
12  * Definition items:
13  * - options callback: The function to call in order to generate the value options. If omitted, the options 'Yes' and 'No' will be used.
14  * - options arguments: An array of arguments to pass to the options callback.
15  *
16  * @ViewsField("machine_name")
17  */
18 class MachineName extends FieldPluginBase {
19
20   /**
21    * @var array Stores the available options.
22    */
23   protected $valueOptions;
24
25   public function getValueOptions() {
26     if (isset($this->valueOptions)) {
27       return;
28     }
29
30     if (isset($this->definition['options callback']) && is_callable($this->definition['options callback'])) {
31       if (isset($this->definition['options arguments']) && is_array($this->definition['options arguments'])) {
32         $this->valueOptions = call_user_func_array($this->definition['options callback'], $this->definition['options arguments']);
33       }
34       else {
35         $this->valueOptions = call_user_func($this->definition['options callback']);
36       }
37     }
38     else {
39       $this->valueOptions = [];
40     }
41   }
42
43   /**
44    * {@inheritdoc}
45    */
46   protected function defineOptions() {
47     $options = parent::defineOptions();
48     $options['machine_name'] = ['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['machine_name'] = [
60       '#title' => $this->t('Output machine name'),
61       '#description' => $this->t('Display field as machine name.'),
62       '#type' => 'checkbox',
63       '#default_value' => !empty($this->options['machine_name']),
64     ];
65   }
66
67   /**
68    * {@inheritdoc}
69    */
70   public function preRender(&$values) {
71     $this->getValueOptions();
72   }
73
74   /**
75    * {@inheritdoc}
76    */
77   public function render(ResultRow $values) {
78     $value = $values->{$this->field_alias};
79     if (!empty($this->options['machine_name']) || !isset($this->valueOptions[$value])) {
80       $result = $this->sanitizeValue($value);
81     }
82     else {
83       $result = $this->valueOptions[$value];
84     }
85
86     return $result;
87   }
88
89 }