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