Table.php 13.5 KB
Newer Older
merlinofchaos's avatar
merlinofchaos committed
1 2 3 4
<?php

/**
 * @file
5
 * Definition of Drupal\views\Plugin\views\style\Table.
merlinofchaos's avatar
merlinofchaos committed
6 7
 */

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

10
use Drupal\Component\Plugin\Discovery\DiscoveryInterface;
11
use Drupal\views\Plugin\views\wizard\WizardInterface;
12
use Drupal\Component\Annotation\Plugin;
13
use Drupal\Core\Annotation\Translation;
14 15
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
16

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

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

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

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

merlinofchaos's avatar
merlinofchaos committed
53 54 55 56 57 58 59 60 61 62 63 64
  /**
   * Contains the current active sort column.
   * @var string
   */
  public $active;

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

65 66 67 68 69 70 71 72
  /**
   * Contains the current request object.
   *
   * @var \Symfony\Component\HttpFoundation\Request
   */
  protected $request;

  /**
73
   * {@inheritdoc}
74 75 76 77 78 79 80 81 82 83 84 85 86 87
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, array $plugin_definition) {
    return new static($configuration, $plugin_id, $plugin_definition, $container->get('request'));
  }

  /**
   * Constructs a Table object.
   */
  public function __construct(array $configuration, $plugin_id, array $plugin_definition, Request $request) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);

    $this->request = $request;
  }

88 89
  protected function defineOptions() {
    $options = parent::defineOptions();
merlinofchaos's avatar
merlinofchaos committed
90 91 92 93 94 95 96 97 98 99 100 101 102 103

    $options['columns'] = array('default' => array());
    $options['default'] = array('default' => '');
    $options['info'] = array('default' => array());
    $options['override'] = array('default' => TRUE, 'bool' => TRUE);
    $options['sticky'] = array('default' => FALSE, 'bool' => TRUE);
    $options['order'] = array('default' => 'asc');
    $options['summary'] = array('default' => '', 'translatable' => TRUE);
    $options['empty_table'] = array('default' => FALSE, 'bool' => TRUE);

    return $options;
  }

  /**
104
   * {@inheritdoc}
merlinofchaos's avatar
merlinofchaos committed
105 106
   */
  function build_sort() {
107
    $order = $this->request->query->get('order');
108
    if (!isset($order) && ($this->options['default'] == -1 || empty($this->view->field[$this->options['default']]))) {
merlinofchaos's avatar
merlinofchaos committed
109 110 111 112
      return TRUE;
    }

    // If a sort we don't know anything about gets through, exit gracefully.
113
    if (isset($order) && empty($this->view->field[$order])) {
merlinofchaos's avatar
merlinofchaos committed
114 115 116 117 118 119 120 121 122 123 124
      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
   */
  function build_sort_post() {
125
    $query = $this->request->query;
126 127
    $order = $query->get('order');
    if (!isset($order)) {
merlinofchaos's avatar
merlinofchaos committed
128 129 130 131 132 133 134 135 136 137 138 139 140
      // 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 {
141
      $sort = $order;
merlinofchaos's avatar
merlinofchaos committed
142
      // Store the $order for later use.
143 144
      $request_sort = $query->get('sort');
      $this->order = !empty($request_sort) ? strtolower($request_sort) : 'asc';
merlinofchaos's avatar
merlinofchaos committed
145 146 147 148 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 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
    }

    // 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.
    $this->view->field[$sort]->click_sort($this->order);
  }

  /**
   * 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.
   */
  function sanitize_columns($columns, $fields = NULL) {
    $sanitized = array();
    if ($fields === NULL) {
191
      $fields = $this->displayHandler->getOption('fields');
merlinofchaos's avatar
merlinofchaos committed
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
    }
    // 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.
   */
222 223
  public function buildOptionsForm(&$form, &$form_state) {
    parent::buildOptionsForm($form, $form_state);
224
    $handlers = $this->displayHandler->getHandlers('field');
merlinofchaos's avatar
merlinofchaos committed
225 226
    if (empty($handlers)) {
      $form['error_markup'] = array(
227
        '#markup' => '<div class="messages messages--error">' . t('You need at least one field before you can configure your table settings') . '</div>',
merlinofchaos's avatar
merlinofchaos committed
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
      );
      return;
    }

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

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

    $form['summary'] = array(
      '#type' => 'textfield',
      '#title' => t('Table summary'),
      '#description' => t('This value will be displayed as table-summary attribute in the html. Set this for better accessiblity of your site.'),
      '#default_value' => $this->options['summary'],
      '#maxlength' => 255,
    );

    // 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';

    $columns = $this->sanitize_columns($this->options['columns']);

    // Create an array of allowed columns from the data we know:
260
    $field_names = $this->displayHandler->getFieldLabels();
merlinofchaos's avatar
merlinofchaos committed
261 262 263 264 265 266 267 268 269 270 271 272

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

    foreach ($columns as $field => $column) {
273
      $column_selector = ':input[name="style_options[columns][' . $field . ']"]';
merlinofchaos's avatar
merlinofchaos committed
274 275 276 277 278 279 280 281 282 283

      $form['columns'][$field] = array(
        '#type' => 'select',
        '#options' => $field_names,
        '#default_value' => $column,
      );
      if ($handlers[$field]->click_sortable()) {
        $form['info'][$field]['sortable'] = array(
          '#type' => 'checkbox',
          '#default_value' => !empty($this->options['info'][$field]['sortable']),
284 285 286 287 288
          '#states' => array(
            'visible' => array(
              $column_selector => array('value' => $field),
            ),
          ),
merlinofchaos's avatar
merlinofchaos committed
289 290 291 292 293
        );
        $form['info'][$field]['default_sort_order'] = array(
          '#type' => 'select',
          '#options' => array('asc' => t('Ascending'), 'desc' => t('Descending')),
          '#default_value' => !empty($this->options['info'][$field]['default_sort_order']) ? $this->options['info'][$field]['default_sort_order'] : 'asc',
294 295 296 297 298 299
          '#states' => array(
            'visible' => array(
              $column_selector => array('value' => $field),
              ':input[name="style_options[info][' . $field . '][sortable]"]' => array('checked' => TRUE),
            ),
          ),
merlinofchaos's avatar
merlinofchaos committed
300 301 302 303 304 305 306 307 308 309 310
        );
        // Provide an ID so we can have such things.
        $radio_id = drupal_html_id('edit-default-' . $field);
        $form['default'][$field] = array(
          '#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,
311 312 313 314 315
          '#states' => array(
            'visible' => array(
              $column_selector => array('value' => $field),
            ),
          ),
merlinofchaos's avatar
merlinofchaos committed
316 317 318 319 320 321 322 323 324 325 326
        );
      }
      $form['info'][$field]['align'] = array(
        '#type' => 'select',
        '#default_value' => !empty($this->options['info'][$field]['align']) ? $this->options['info'][$field]['align'] : '',
        '#options' => array(
          '' => t('None'),
          'views-align-left' => t('Left'),
          'views-align-center' => t('Center'),
          'views-align-right' => t('Right'),
          ),
327 328 329 330 331
        '#states' => array(
          'visible' => array(
            $column_selector => array('value' => $field),
          ),
        ),
merlinofchaos's avatar
merlinofchaos committed
332 333 334 335 336
      );
      $form['info'][$field]['separator'] = array(
        '#type' => 'textfield',
        '#size' => 10,
        '#default_value' => isset($this->options['info'][$field]['separator']) ? $this->options['info'][$field]['separator'] : '',
337 338 339 340 341
        '#states' => array(
          'visible' => array(
            $column_selector => array('value' => $field),
          ),
        ),
merlinofchaos's avatar
merlinofchaos committed
342 343 344 345
      );
      $form['info'][$field]['empty_column'] = array(
        '#type' => 'checkbox',
        '#default_value' => isset($this->options['info'][$field]['empty_column']) ? $this->options['info'][$field]['empty_column'] : FALSE,
346 347 348 349 350
        '#states' => array(
          'visible' => array(
            $column_selector => array('value' => $field),
          ),
        ),
merlinofchaos's avatar
merlinofchaos committed
351
      );
352 353 354
      $form['info'][$field]['responsive'] = array(
        '#type' => 'select',
        '#default_value' => isset($this->options['info'][$field]['responsive']) ? $this->options['info'][$field]['responsive'] : '',
355
        '#options' => array('' => t('High'), RESPONSIVE_PRIORITY_MEDIUM => t('Medium'), RESPONSIVE_PRIORITY_LOW => t('Low')),
356 357 358 359 360 361
        '#states' => array(
          'visible' => array(
            $column_selector => array('value' => $field),
          ),
        ),
      );
merlinofchaos's avatar
merlinofchaos committed
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392

      // 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(
      '#type' => 'radio',
      '#return_value' => -1,
      '#parents' => array('style_options', 'default'),
      '#id' => 'edit-default-0',
      '#default_value' => $default,
    );

    $form['empty_table'] = array(
      '#type' => 'checkbox',
      '#title' => t('Show the empty text in the table'),
      '#default_value' => $this->options['empty_table'],
      '#description' => t('Per default the table is hidden for an empty view. With this option it is posible to show an empty table with the text in it.'),
    );

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

  function even_empty() {
    return parent::even_empty() || !empty($this->options['empty_table']);
  }
393

394 395 396 397 398 399 400 401 402
  function wizard_submit(&$form, &$form_state, WizardInterface $wizard, &$display_options, $display_type) {
    // If any of the displays use the table style, take sure that the fields
    // always have a labels by unsetting the override.
    foreach ($display_options['default']['fields'] as &$field) {
      unset($field['label']);
    }
  }


merlinofchaos's avatar
merlinofchaos committed
403
}