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