Upgraded drupal core with security updates
[yaffs-website] / web / core / modules / views / src / Plugin / views / style / Table.php
1 <?php
2
3 namespace Drupal\views\Plugin\views\style;
4
5 use Drupal\Component\Utility\Html;
6 use Drupal\Core\Cache\CacheableDependencyInterface;
7 use Drupal\Core\Form\FormStateInterface;
8 use Drupal\views\Plugin\views\wizard\WizardInterface;
9
10 /**
11  * Style plugin to render each item as a row in a table.
12  *
13  * @ingroup views_style_plugins
14  *
15  * @ViewsStyle(
16  *   id = "table",
17  *   title = @Translation("Table"),
18  *   help = @Translation("Displays rows in a table."),
19  *   theme = "views_view_table",
20  *   display_types = {"normal"}
21  * )
22  */
23 class Table extends StylePluginBase implements CacheableDependencyInterface {
24
25   /**
26    * Does the style plugin for itself support to add fields to it's output.
27    *
28    * @var bool
29    */
30   protected $usesFields = TRUE;
31
32   /**
33    * {@inheritdoc}
34    */
35   protected $usesRowPlugin = FALSE;
36
37   /**
38    * Does the style plugin support custom css class for the rows.
39    *
40    * @var bool
41    */
42   protected $usesRowClass = TRUE;
43
44   /**
45    * Should field labels be enabled by default.
46    *
47    * @var bool
48    */
49   protected $defaultFieldLabels = TRUE;
50
51   /**
52    * Contains the current active sort column.
53    * @var string
54    */
55   public $active;
56
57   /**
58    * Contains the current active sort order, either desc or asc.
59    * @var string
60    */
61   public $order;
62
63   protected function defineOptions() {
64     $options = parent::defineOptions();
65
66     $options['columns'] = ['default' => []];
67     $options['default'] = ['default' => ''];
68     $options['info'] = ['default' => []];
69     $options['override'] = ['default' => TRUE];
70     $options['sticky'] = ['default' => FALSE];
71     $options['order'] = ['default' => 'asc'];
72     $options['caption'] = ['default' => ''];
73     $options['summary'] = ['default' => ''];
74     $options['description'] = ['default' => ''];
75     $options['empty_table'] = ['default' => FALSE];
76
77     return $options;
78   }
79
80   /**
81    * {@inheritdoc}
82    */
83   public function buildSort() {
84     $order = $this->view->getRequest()->query->get('order');
85     if (!isset($order) && ($this->options['default'] == -1 || empty($this->view->field[$this->options['default']]))) {
86       return TRUE;
87     }
88
89     // If a sort we don't know anything about gets through, exit gracefully.
90     if (isset($order) && empty($this->view->field[$order])) {
91       return TRUE;
92     }
93
94     // Let the builder know whether or not we're overriding the default sorts.
95     return empty($this->options['override']);
96   }
97
98   /**
99    * Add our actual sort criteria
100    */
101   public function buildSortPost() {
102     $query = $this->view->getRequest()->query;
103     $order = $query->get('order');
104     if (!isset($order)) {
105       // check for a 'default' clicksort. If there isn't one, exit gracefully.
106       if (empty($this->options['default'])) {
107         return;
108       }
109       $sort = $this->options['default'];
110       if (!empty($this->options['info'][$sort]['default_sort_order'])) {
111         $this->order = $this->options['info'][$sort]['default_sort_order'];
112       }
113       else {
114         $this->order = !empty($this->options['order']) ? $this->options['order'] : 'asc';
115       }
116     }
117     else {
118       $sort = $order;
119       // Store the $order for later use.
120       $request_sort = $query->get('sort');
121       $this->order = !empty($request_sort) ? strtolower($request_sort) : 'asc';
122     }
123
124     // If a sort we don't know anything about gets through, exit gracefully.
125     if (empty($this->view->field[$sort])) {
126       return;
127     }
128
129     // Ensure $this->order is valid.
130     if ($this->order != 'asc' && $this->order != 'desc') {
131       $this->order = 'asc';
132     }
133
134     // Store the $sort for later use.
135     $this->active = $sort;
136
137     // Tell the field to click sort.
138     $this->view->field[$sort]->clickSort($this->order);
139   }
140
141   /**
142    * Normalize a list of columns based upon the fields that are
143    * available. This compares the fields stored in the style handler
144    * to the list of fields actually in the view, removing fields that
145    * have been removed and adding new fields in their own column.
146    *
147    * - Each field must be in a column.
148    * - Each column must be based upon a field, and that field
149    *   is somewhere in the column.
150    * - Any fields not currently represented must be added.
151    * - Columns must be re-ordered to match the fields.
152    *
153    * @param $columns
154    *   An array of all fields; the key is the id of the field and the
155    *   value is the id of the column the field should be in.
156    * @param $fields
157    *   The fields to use for the columns. If not provided, they will
158    *   be requested from the current display. The running render should
159    *   send the fields through, as they may be different than what the
160    *   display has listed due to access control or other changes.
161    *
162    * @return array
163    *    An array of all the sanitized columns.
164    */
165   public function sanitizeColumns($columns, $fields = NULL) {
166     $sanitized = [];
167     if ($fields === NULL) {
168       $fields = $this->displayHandler->getOption('fields');
169     }
170     // Preconfigure the sanitized array so that the order is retained.
171     foreach ($fields as $field => $info) {
172       // Set to itself so that if it isn't touched, it gets column
173       // status automatically.
174       $sanitized[$field] = $field;
175     }
176
177     foreach ($columns as $field => $column) {
178       // first, make sure the field still exists.
179       if (!isset($sanitized[$field])) {
180         continue;
181       }
182
183       // If the field is the column, mark it so, or the column
184       // it's set to is a column, that's ok
185       if ($field == $column || $columns[$column] == $column && !empty($sanitized[$column])) {
186         $sanitized[$field] = $column;
187       }
188       // Since we set the field to itself initially, ignoring
189       // the condition is ok; the field will get its column
190       // status back.
191     }
192
193     return $sanitized;
194   }
195
196   /**
197    * Render the given style.
198    */
199   public function buildOptionsForm(&$form, FormStateInterface $form_state) {
200     parent::buildOptionsForm($form, $form_state);
201     $handlers = $this->displayHandler->getHandlers('field');
202     if (empty($handlers)) {
203       $form['error_markup'] = [
204         '#markup' => '<div class="messages messages--error">' . $this->t('You need at least one field before you can configure your table settings') . '</div>',
205       ];
206       return;
207     }
208
209     $form['override'] = [
210       '#type' => 'checkbox',
211       '#title' => $this->t('Override normal sorting if click sorting is used'),
212       '#default_value' => !empty($this->options['override']),
213     ];
214
215     $form['sticky'] = [
216       '#type' => 'checkbox',
217       '#title' => $this->t('Enable Drupal style "sticky" table headers (Javascript)'),
218       '#default_value' => !empty($this->options['sticky']),
219       '#description' => $this->t('(Sticky header effects will not be active for preview below, only on live output.)'),
220     ];
221
222     $form['caption'] = [
223       '#type' => 'textfield',
224       '#title' => $this->t('Caption for the table'),
225       '#description' => $this->t('A title semantically associated with your table for increased accessibility.'),
226       '#default_value' => $this->options['caption'],
227       '#maxlength' => 255,
228     ];
229
230     $form['accessibility_details'] = [
231       '#type' => 'details',
232       '#title' => $this->t('Table details'),
233     ];
234
235     $form['summary'] = [
236       '#title' => $this->t('Summary title'),
237       '#type' => 'textfield',
238       '#default_value' => $this->options['summary'],
239       '#fieldset' => 'accessibility_details',
240     ];
241
242     $form['description'] = [
243       '#title' => $this->t('Table description'),
244       '#type' => 'textarea',
245       '#description' => $this->t('Provide additional details about the table to increase accessibility.'),
246       '#default_value' => $this->options['description'],
247       '#states' => [
248         'visible' => [
249           'input[name="style_options[summary]"]' => ['filled' => TRUE],
250         ],
251       ],
252       '#fieldset' => 'accessibility_details',
253     ];
254
255     // Note: views UI registers this theme handler on our behalf. Your module
256     // will have to register your theme handlers if you do stuff like this.
257     $form['#theme'] = 'views_ui_style_plugin_table';
258
259     $columns = $this->sanitizeColumns($this->options['columns']);
260
261     // Create an array of allowed columns from the data we know:
262     $field_names = $this->displayHandler->getFieldLabels();
263
264     if (isset($this->options['default'])) {
265       $default = $this->options['default'];
266       if (!isset($columns[$default])) {
267         $default = -1;
268       }
269     }
270     else {
271       $default = -1;
272     }
273
274     foreach ($columns as $field => $column) {
275       $column_selector = ':input[name="style_options[columns][' . $field . ']"]';
276
277       $form['columns'][$field] = [
278         '#title' => $this->t('Columns for @field', ['@field' => $field]),
279         '#title_display' => 'invisible',
280         '#type' => 'select',
281         '#options' => $field_names,
282         '#default_value' => $column,
283       ];
284       if ($handlers[$field]->clickSortable()) {
285         $form['info'][$field]['sortable'] = [
286           '#title' => $this->t('Sortable for @field', ['@field' => $field]),
287           '#title_display' => 'invisible',
288           '#type' => 'checkbox',
289           '#default_value' => !empty($this->options['info'][$field]['sortable']),
290           '#states' => [
291             'visible' => [
292               $column_selector => ['value' => $field],
293             ],
294           ],
295         ];
296         $form['info'][$field]['default_sort_order'] = [
297           '#title' => $this->t('Default sort order for @field', ['@field' => $field]),
298           '#title_display' => 'invisible',
299           '#type' => 'select',
300           '#options' => ['asc' => $this->t('Ascending'), 'desc' => $this->t('Descending')],
301           '#default_value' => !empty($this->options['info'][$field]['default_sort_order']) ? $this->options['info'][$field]['default_sort_order'] : 'asc',
302           '#states' => [
303             'visible' => [
304               $column_selector => ['value' => $field],
305               ':input[name="style_options[info][' . $field . '][sortable]"]' => ['checked' => TRUE],
306             ],
307           ],
308         ];
309         // Provide an ID so we can have such things.
310         $radio_id = Html::getUniqueId('edit-default-' . $field);
311         $form['default'][$field] = [
312           '#title' => $this->t('Default sort for @field', ['@field' => $field]),
313           '#title_display' => 'invisible',
314           '#type' => 'radio',
315           '#return_value' => $field,
316           '#parents' => ['style_options', 'default'],
317           '#id' => $radio_id,
318           // because 'radio' doesn't fully support '#id' =(
319           '#attributes' => ['id' => $radio_id],
320           '#default_value' => $default,
321           '#states' => [
322             'visible' => [
323               $column_selector => ['value' => $field],
324             ],
325           ],
326         ];
327       }
328       $form['info'][$field]['align'] = [
329         '#title' => $this->t('Alignment for @field', ['@field' => $field]),
330         '#title_display' => 'invisible',
331         '#type' => 'select',
332         '#default_value' => !empty($this->options['info'][$field]['align']) ? $this->options['info'][$field]['align'] : '',
333         '#options' => [
334           '' => $this->t('None'),
335           'views-align-left' => $this->t('Left', [], ['context' => 'Text alignment']),
336           'views-align-center' => $this->t('Center', [], ['context' => 'Text alignment']),
337           'views-align-right' => $this->t('Right', [], ['context' => 'Text alignment']),
338           ],
339         '#states' => [
340           'visible' => [
341             $column_selector => ['value' => $field],
342           ],
343         ],
344       ];
345       $form['info'][$field]['separator'] = [
346         '#title' => $this->t('Separator for @field', ['@field' => $field]),
347         '#title_display' => 'invisible',
348         '#type' => 'textfield',
349         '#size' => 10,
350         '#default_value' => isset($this->options['info'][$field]['separator']) ? $this->options['info'][$field]['separator'] : '',
351         '#states' => [
352           'visible' => [
353             $column_selector => ['value' => $field],
354           ],
355         ],
356       ];
357       $form['info'][$field]['empty_column'] = [
358         '#title' => $this->t('Hide empty column for @field', ['@field' => $field]),
359         '#title_display' => 'invisible',
360         '#type' => 'checkbox',
361         '#default_value' => isset($this->options['info'][$field]['empty_column']) ? $this->options['info'][$field]['empty_column'] : FALSE,
362         '#states' => [
363           'visible' => [
364             $column_selector => ['value' => $field],
365           ],
366         ],
367       ];
368       $form['info'][$field]['responsive'] = [
369         '#title' => $this->t('Responsive setting for @field', ['@field' => $field]),
370         '#title_display' => 'invisible',
371         '#type' => 'select',
372         '#default_value' => isset($this->options['info'][$field]['responsive']) ? $this->options['info'][$field]['responsive'] : '',
373         '#options' => ['' => $this->t('High'), RESPONSIVE_PRIORITY_MEDIUM => $this->t('Medium'), RESPONSIVE_PRIORITY_LOW => $this->t('Low')],
374         '#states' => [
375           'visible' => [
376             $column_selector => ['value' => $field],
377           ],
378         ],
379       ];
380
381       // markup for the field name
382       $form['info'][$field]['name'] = [
383         '#markup' => $field_names[$field],
384       ];
385     }
386
387     // Provide a radio for no default sort
388     $form['default'][-1] = [
389       '#title' => $this->t('No default sort'),
390       '#title_display' => 'invisible',
391       '#type' => 'radio',
392       '#return_value' => -1,
393       '#parents' => ['style_options', 'default'],
394       '#id' => 'edit-default-0',
395       '#default_value' => $default,
396     ];
397
398     $form['empty_table'] = [
399       '#type' => 'checkbox',
400       '#title' => $this->t('Show the empty text in the table'),
401       '#default_value' => $this->options['empty_table'],
402       '#description' => $this->t('Per default the table is hidden for an empty view. With this option it is possible to show an empty table with the text in it.'),
403     ];
404
405     $form['description_markup'] = [
406       '#markup' => '<div class="js-form-item form-item description">' . $this->t('Place fields into columns; you may combine multiple fields into the same column. If you do, the separator in the column specified will be used to separate the fields. Check the sortable box to make that column click sortable, and check the default sort radio to determine which column will be sorted by default, if any. You may control column order and field labels in the fields section.') . '</div>',
407     ];
408   }
409
410   public function evenEmpty() {
411     return parent::evenEmpty() || !empty($this->options['empty_table']);
412   }
413
414   public function wizardSubmit(&$form, FormStateInterface $form_state, WizardInterface $wizard, &$display_options, $display_type) {
415     // If any of the displays use the table style, make sure that the fields
416     // always have a labels by unsetting the override.
417     foreach ($display_options['default']['fields'] as &$field) {
418       unset($field['label']);
419     }
420   }
421
422   /**
423    * {@inheritdoc}
424    */
425   public function getCacheMaxAge() {
426     return 0;
427   }
428
429   /**
430    * {@inheritdoc}
431    */
432   public function getCacheContexts() {
433     $contexts = [];
434
435     foreach ($this->options['info'] as $field_id => $info) {
436       if (!empty($info['sortable'])) {
437         // The rendered link needs to play well with any other query parameter
438         // used on the page, like pager and exposed filter.
439         $contexts[] = 'url.query_args';
440         break;
441       }
442     }
443
444     return $contexts;
445   }
446
447   /**
448    * {@inheritdoc}
449    */
450   public function getCacheTags() {
451     return [];
452   }
453
454 }