Table.php 15.8 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Contains \Drupal\views\Plugin\views\style\Table.
6 7
 */

8
namespace Drupal\views\Plugin\views\style;
9

10
use Drupal\Component\Plugin\Discovery\DiscoveryInterface;
11
use Drupal\Component\Utility\Html;
12
use Drupal\Core\Form\FormStateInterface;
13
use Drupal\views\Plugin\CacheablePluginInterface;
14
use Drupal\views\Plugin\views\wizard\WizardInterface;
15 16
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
17

18 19 20 21
/**
 * Style plugin to render each item as a row in a table.
 *
 * @ingroup views_style_plugins
22
 *
23
 * @ViewsStyle(
aspilicious's avatar
aspilicious committed
24
 *   id = "table",
25 26 27
 *   title = @Translation("Table"),
 *   help = @Translation("Displays rows in a table."),
 *   theme = "views_view_table",
28
 *   display_types = {"normal"}
29 30
 * )
 */
31
class Table extends StylePluginBase implements CacheablePluginInterface {
32

33 34 35 36 37
  /**
   * Does the style plugin for itself support to add fields to it's output.
   *
   * @var bool
   */
38
  protected $usesFields = TRUE;
39 40 41 42 43 44

  /**
   * Does the style plugin allows to use style plugins.
   *
   * @var bool
   */
45
  protected $usesRowPlugin = FALSE;
46 47 48 49 50 51

  /**
   * Does the style plugin support custom css class for the rows.
   *
   * @var bool
   */
52
  protected $usesRowClass = TRUE;
53

54 55 56 57 58 59 60
  /**
   * Should field labels be enabled by default.
   *
   * @var bool
   */
  protected $defaultFieldLabels = TRUE;

61 62 63 64 65 66 67 68 69 70 71 72
  /**
   * Contains the current active sort column.
   * @var string
   */
  public $active;

  /**
   * Contains the current active sort order, either desc or asc.
   * @var string
   */
  public $order;

73 74
  protected function defineOptions() {
    $options = parent::defineOptions();
75 76 77 78

    $options['columns'] = array('default' => array());
    $options['default'] = array('default' => '');
    $options['info'] = array('default' => array());
79 80
    $options['override'] = array('default' => TRUE);
    $options['sticky'] = array('default' => FALSE);
81
    $options['order'] = array('default' => 'asc');
82 83 84 85
    $options['caption'] = array('default' => '');
    $options['summary'] = array('default' => '');
    $options['description'] = array('default' => '');
    $options['empty_table'] = array('default' => FALSE);
86 87 88 89 90

    return $options;
  }

  /**
91
   * {@inheritdoc}
92
   */
93
  public function buildSort() {
94
    $order = $this->view->getRequest()->query->get('order');
95
    if (!isset($order) && ($this->options['default'] == -1 || empty($this->view->field[$this->options['default']]))) {
96 97 98 99
      return TRUE;
    }

    // If a sort we don't know anything about gets through, exit gracefully.
100
    if (isset($order) && empty($this->view->field[$order])) {
101 102 103 104 105 106 107 108 109 110
      return TRUE;
    }

    // Let the builder know whether or not we're overriding the default sorts.
    return empty($this->options['override']);
  }

  /**
   * Add our actual sort criteria
   */
111
  public function buildSortPost() {
112
    $query = $this->view->getRequest()->query;
113 114
    $order = $query->get('order');
    if (!isset($order)) {
115 116 117 118 119 120 121 122 123 124 125 126 127
      // check for a 'default' clicksort. If there isn't one, exit gracefully.
      if (empty($this->options['default'])) {
        return;
      }
      $sort = $this->options['default'];
      if (!empty($this->options['info'][$sort]['default_sort_order'])) {
        $this->order = $this->options['info'][$sort]['default_sort_order'];
      }
      else {
        $this->order = !empty($this->options['order']) ? $this->options['order'] : 'asc';
      }
    }
    else {
128
      $sort = $order;
129
      // Store the $order for later use.
130 131
      $request_sort = $query->get('sort');
      $this->order = !empty($request_sort) ? strtolower($request_sort) : 'asc';
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
    }

    // If a sort we don't know anything about gets through, exit gracefully.
    if (empty($this->view->field[$sort])) {
      return;
    }

    // Ensure $this->order is valid.
    if ($this->order != 'asc' && $this->order != 'desc') {
      $this->order = 'asc';
    }

    // Store the $sort for later use.
    $this->active = $sort;

    // Tell the field to click sort.
148
    $this->view->field[$sort]->clickSort($this->order);
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
  }

  /**
   * Normalize a list of columns based upon the fields that are
   * available. This compares the fields stored in the style handler
   * to the list of fields actually in the view, removing fields that
   * have been removed and adding new fields in their own column.
   *
   * - Each field must be in a column.
   * - Each column must be based upon a field, and that field
   *   is somewhere in the column.
   * - Any fields not currently represented must be added.
   * - Columns must be re-ordered to match the fields.
   *
   * @param $columns
   *   An array of all fields; the key is the id of the field and the
   *   value is the id of the column the field should be in.
   * @param $fields
   *   The fields to use for the columns. If not provided, they will
   *   be requested from the current display. The running render should
   *   send the fields through, as they may be different than what the
   *   display has listed due to access control or other changes.
   *
   * @return array
   *    An array of all the sanitized columns.
   */
175
  public function sanitizeColumns($columns, $fields = NULL) {
176 177
    $sanitized = array();
    if ($fields === NULL) {
178
      $fields = $this->displayHandler->getOption('fields');
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
    }
    // Preconfigure the sanitized array so that the order is retained.
    foreach ($fields as $field => $info) {
      // Set to itself so that if it isn't touched, it gets column
      // status automatically.
      $sanitized[$field] = $field;
    }

    foreach ($columns as $field => $column) {
      // first, make sure the field still exists.
      if (!isset($sanitized[$field])) {
        continue;
      }

      // If the field is the column, mark it so, or the column
      // it's set to is a column, that's ok
      if ($field == $column || $columns[$column] == $column && !empty($sanitized[$column])) {
        $sanitized[$field] = $column;
      }
      // Since we set the field to itself initially, ignoring
      // the condition is ok; the field will get its column
      // status back.
    }

    return $sanitized;
  }

  /**
   * Render the given style.
   */
209
  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
210
    parent::buildOptionsForm($form, $form_state);
211
    $handlers = $this->displayHandler->getHandlers('field');
212 213
    if (empty($handlers)) {
      $form['error_markup'] = array(
214
        '#markup' => '<div class="messages messages--error">' . $this->t('You need at least one field before you can configure your table settings') . '</div>',
215 216 217 218 219 220
      );
      return;
    }

    $form['override'] = array(
      '#type' => 'checkbox',
221
      '#title' => $this->t('Override normal sorting if click sorting is used'),
222 223 224 225 226
      '#default_value' => !empty($this->options['override']),
    );

    $form['sticky'] = array(
      '#type' => 'checkbox',
227
      '#title' => $this->t('Enable Drupal style "sticky" table headers (Javascript)'),
228
      '#default_value' => !empty($this->options['sticky']),
229
      '#description' => $this->t('(Sticky header effects will not be active for preview below, only on live output.)'),
230 231
    );

232 233
    $form['caption'] = array(
      '#type' => 'textfield',
234 235
      '#title' => $this->t('Caption for the table'),
      '#description' => $this->t('A title which is semantically associated to your table for increased accessibility.'),
236 237 238 239 240 241
      '#default_value' => $this->options['caption'],
      '#maxlength' => 255,
    );

    $form['accessibility_details'] = array(
      '#type' => 'details',
242
      '#title' => $this->t('Table details'),
243 244
    );

245
    $form['summary'] = array(
246
      '#title' => $this->t('Summary title'),
247 248
      '#type' => 'textfield',
      '#default_value' => $this->options['summary'],
249 250 251 252
      '#fieldset' => 'accessibility_details',
    );

    $form['description'] = array(
253
      '#title' => $this->t('Table description'),
254
      '#type' => 'textarea',
255
      '#description' => $this->t('Provide additional details about the table to increase accessibility.'),
256 257 258 259 260 261 262
      '#default_value' => $this->options['description'],
      '#states' => array(
        'visible' => array(
          'input[name="style_options[summary]"]' => array('filled' => TRUE),
        ),
      ),
      '#fieldset' => 'accessibility_details',
263 264 265 266 267 268
    );

    // Note: views UI registers this theme handler on our behalf. Your module
    // will have to register your theme handlers if you do stuff like this.
    $form['#theme'] = 'views_ui_style_plugin_table';

269
    $columns = $this->sanitizeColumns($this->options['columns']);
270 271

    // Create an array of allowed columns from the data we know:
272
    $field_names = $this->displayHandler->getFieldLabels();
273 274 275 276 277 278 279 280 281 282 283 284

    if (isset($this->options['default'])) {
      $default = $this->options['default'];
      if (!isset($columns[$default])) {
        $default = -1;
      }
    }
    else {
      $default = -1;
    }

    foreach ($columns as $field => $column) {
285
      $column_selector = ':input[name="style_options[columns][' . $field . ']"]';
286 287

      $form['columns'][$field] = array(
288
        '#title' => $this->t('Columns for @field', array('@field' => $field)),
289
        '#title_display' => 'invisible',
290 291 292 293
        '#type' => 'select',
        '#options' => $field_names,
        '#default_value' => $column,
      );
294
      if ($handlers[$field]->clickSortable()) {
295
        $form['info'][$field]['sortable'] = array(
296
          '#title' => $this->t('Sortable for @field', array('@field' => $field)),
297
          '#title_display' => 'invisible',
298 299
          '#type' => 'checkbox',
          '#default_value' => !empty($this->options['info'][$field]['sortable']),
300 301 302 303 304
          '#states' => array(
            'visible' => array(
              $column_selector => array('value' => $field),
            ),
          ),
305 306
        );
        $form['info'][$field]['default_sort_order'] = array(
307
          '#title' => $this->t('Default sort order for @field', array('@field' => $field)),
308
          '#title_display' => 'invisible',
309
          '#type' => 'select',
310
          '#options' => array('asc' => $this->t('Ascending'), 'desc' => $this->t('Descending')),
311
          '#default_value' => !empty($this->options['info'][$field]['default_sort_order']) ? $this->options['info'][$field]['default_sort_order'] : 'asc',
312 313 314 315 316 317
          '#states' => array(
            'visible' => array(
              $column_selector => array('value' => $field),
              ':input[name="style_options[info][' . $field . '][sortable]"]' => array('checked' => TRUE),
            ),
          ),
318 319
        );
        // Provide an ID so we can have such things.
320
        $radio_id = Html::getUniqueId('edit-default-' . $field);
321
        $form['default'][$field] = array(
322
          '#title' => $this->t('Default sort for @field', array('@field' => $field)),
323
          '#title_display' => 'invisible',
324 325 326 327 328 329 330
          '#type' => 'radio',
          '#return_value' => $field,
          '#parents' => array('style_options', 'default'),
          '#id' => $radio_id,
          // because 'radio' doesn't fully support '#id' =(
          '#attributes' => array('id' => $radio_id),
          '#default_value' => $default,
331 332 333 334 335
          '#states' => array(
            'visible' => array(
              $column_selector => array('value' => $field),
            ),
          ),
336 337 338
        );
      }
      $form['info'][$field]['align'] = array(
339
        '#title' => $this->t('Alignment for @field', array('@field' => $field)),
340
        '#title_display' => 'invisible',
341 342 343
        '#type' => 'select',
        '#default_value' => !empty($this->options['info'][$field]['align']) ? $this->options['info'][$field]['align'] : '',
        '#options' => array(
344 345 346 347
          '' => $this->t('None'),
          'views-align-left' => $this->t('Left', array(), array('context' => 'Text alignment')),
          'views-align-center' => $this->t('Center', array(), array('context' => 'Text alignment')),
          'views-align-right' => $this->t('Right', array(), array('context' => 'Text alignment')),
348
          ),
349 350 351 352 353
        '#states' => array(
          'visible' => array(
            $column_selector => array('value' => $field),
          ),
        ),
354 355
      );
      $form['info'][$field]['separator'] = array(
356
        '#title' => $this->t('Separator for @field', array('@field' => $field)),
357
        '#title_display' => 'invisible',
358 359 360
        '#type' => 'textfield',
        '#size' => 10,
        '#default_value' => isset($this->options['info'][$field]['separator']) ? $this->options['info'][$field]['separator'] : '',
361 362 363 364 365
        '#states' => array(
          'visible' => array(
            $column_selector => array('value' => $field),
          ),
        ),
366 367
      );
      $form['info'][$field]['empty_column'] = array(
368
        '#title' => $this->t('Hide empty column for @field', array('@field' => $field)),
369
        '#title_display' => 'invisible',
370 371
        '#type' => 'checkbox',
        '#default_value' => isset($this->options['info'][$field]['empty_column']) ? $this->options['info'][$field]['empty_column'] : FALSE,
372 373 374 375 376
        '#states' => array(
          'visible' => array(
            $column_selector => array('value' => $field),
          ),
        ),
377
      );
378
      $form['info'][$field]['responsive'] = array(
379
        '#title' => $this->t('Responsive setting for @field', array('@field' => $field)),
380
        '#title_display' => 'invisible',
381 382
        '#type' => 'select',
        '#default_value' => isset($this->options['info'][$field]['responsive']) ? $this->options['info'][$field]['responsive'] : '',
383
        '#options' => array('' => $this->t('High'), RESPONSIVE_PRIORITY_MEDIUM => $this->t('Medium'), RESPONSIVE_PRIORITY_LOW => $this->t('Low')),
384 385 386 387 388 389
        '#states' => array(
          'visible' => array(
            $column_selector => array('value' => $field),
          ),
        ),
      );
390 391 392 393 394 395 396 397 398

      // markup for the field name
      $form['info'][$field]['name'] = array(
        '#markup' => $field_names[$field],
      );
    }

    // Provide a radio for no default sort
    $form['default'][-1] = array(
399
      '#title' => $this->t('No default sort'),
400
      '#title_display' => 'invisible',
401 402 403 404 405 406 407 408 409
      '#type' => 'radio',
      '#return_value' => -1,
      '#parents' => array('style_options', 'default'),
      '#id' => 'edit-default-0',
      '#default_value' => $default,
    );

    $form['empty_table'] = array(
      '#type' => 'checkbox',
410
      '#title' => $this->t('Show the empty text in the table'),
411
      '#default_value' => $this->options['empty_table'],
412
      '#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.'),
413 414 415
    );

    $form['description_markup'] = array(
416
      '#markup' => '<div class="description form-item">' . $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>',
417 418 419
    );
  }

420 421
  public function evenEmpty() {
    return parent::evenEmpty() || !empty($this->options['empty_table']);
422
  }
423

424
  public function wizardSubmit(&$form, FormStateInterface $form_state, WizardInterface $wizard, &$display_options, $display_type) {
425
    // If any of the displays use the table style, make sure that the fields
426 427 428 429 430 431
    // always have a labels by unsetting the override.
    foreach ($display_options['default']['fields'] as &$field) {
      unset($field['label']);
    }
  }

432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
  /**
   * {@inheritdoc}
   */
  public function isCacheable() {
    return TRUE;
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheContexts() {
    $contexts = [];

    foreach ($this->options['info'] as $field_id => $info) {
      if (!empty($info['sortable'])) {
447 448 449
        // The rendered link needs to play well with any other query parameter
        // used on the page, like pager and exposed filter.
        $contexts[] = 'url.query_args';
450 451 452 453 454 455
        break;
      }
    }

    return $contexts;
  }
456

457
}