StylePluginBase.php 26.2 KB
Newer Older
1 2 3 4
<?php

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

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

10
use Drupal\Component\Utility\Html;
11
use Drupal\Component\Utility\Xss;
12
use Drupal\Core\Form\FormStateInterface;
13
use Drupal\Core\Render\Element;
14
use Drupal\Core\Render\SafeString;
15
use Drupal\views\Plugin\views\display\DisplayPluginBase;
16
use Drupal\views\Plugin\views\PluginBase;
17
use Drupal\views\Plugin\views\wizard\WizardInterface;
18
use Drupal\views\ViewExecutable;
19

20 21 22
/**
 * @defgroup views_style_plugins Views style plugins
 * @{
23
 * Plugins that control how the collection of results is rendered in a view.
24
 *
25
 * Style plugins control how a view is displayed. For the most part, they are
26 27 28 29 30 31 32 33 34 35
 * object wrappers around theme templates. Examples of styles include HTML
 * lists, tables, full or teaser content views, etc.
 *
 * Many (but not all) style plugins have an optional row plugin, which
 * displays a single record. Not all style plugins use row plugins, so it is
 * up to the style plugin to set this up and call the row plugin. See the
 * @link views_row_plugins Views row plugins topic @endlink for more
 * information.
 *
 * Style plugins extend \Drupal\views\Plugin\views\style\StylePluginBase. They
36
 * must be annotated with \Drupal\views\Annotation\ViewsStyle
37 38 39 40
 * annotation, and they must be in namespace directory Plugin\views\style.
 *
 * @ingroup views_plugins
 * @see plugin_api
41 42 43
 */

/**
44
 * Base class for views style plugins.
45
 */
46
abstract class StylePluginBase extends PluginBase {
47

48 49 50
  /**
   * Overrides Drupal\views\Plugin\Plugin::$usesOptions.
   */
51
  protected $usesOptions = TRUE;
52

53 54 55
  /**
   * Store all available tokens row rows.
   */
56
  protected $rowTokens = array();
57

58 59 60 61 62
  /**
   * Does the style plugin allows to use style plugins.
   *
   * @var bool
   */
63
  protected $usesRowPlugin = FALSE;
64 65 66 67 68 69

  /**
   * Does the style plugin support custom css class for the rows.
   *
   * @var bool
   */
70
  protected $usesRowClass = FALSE;
71

72 73 74 75 76 77 78
  /**
   * Does the style plugin support grouping of rows.
   *
   * @var bool
   */
  protected $usesGrouping = TRUE;

79 80 81 82 83 84 85 86
  /**
   * Does the style plugin for itself support to add fields to it's output.
   *
   * This option only makes sense on style plugins without row plugins, like
   * for example table.
   *
   * @var bool
   */
87
  protected $usesFields = FALSE;
88

89
  /**
90 91 92 93 94 95 96
   * Stores the rendered field values, keyed by the row index and field name.
   *
   * @see \Drupal\views\Plugin\views\style\StylePluginBase::renderFields()
   * @see \Drupal\views\Plugin\views\style\StylePluginBase::getField()
   *
   * @var array|null
   */
97 98
  protected $rendered_fields;

99 100 101 102 103 104 105 106
  /**
   * The theme function used to render the grouping set.
   *
   * Plugins may override this attribute if they wish to use some other theme
   * function to render the grouping set.
   *
   * @var string
   *
107
   * @see StylePluginBase::renderGroupingSets()
108 109 110
   */
  protected $groupingTheme = 'views_view_grouping';

111 112 113 114 115 116 117
  /**
   * Should field labels be enabled by default.
   *
   * @var bool
   */
  protected $defaultFieldLabels = FALSE;

118
  /**
119
   * Overrides \Drupal\views\Plugin\views\PluginBase::init().
120
   *
121 122
   * The style options might come externally as the style can be sourced from at
   * least two locations. If it's not included, look on the display.
123
   */
124 125
  public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
    parent::init($view, $display, $options);
126

127
    if ($this->usesRowPlugin() && $display->getOption('row')) {
128
      $this->view->rowPlugin = $display->getPlugin('row');
129 130 131 132 133 134 135 136
    }

    $this->options += array(
      'grouping' => array(),
    );

  }

137
  public function destroy() {
138 139
    parent::destroy();

140 141
    if (isset($this->view->rowPlugin)) {
      $this->view->rowPlugin->destroy();
142 143 144 145
    }
  }

  /**
146 147 148
   * Returns the usesRowPlugin property.
   *
   * @return bool
149
   */
150 151 152
  function usesRowPlugin() {
    return $this->usesRowPlugin;

153 154 155
  }

  /**
156 157 158
   * Returns the usesRowClass property.
   *
   * @return bool
159
   */
160 161
  function usesRowClass() {
    return $this->usesRowClass;
162 163
  }

164 165 166 167 168 169 170 171 172
  /**
   * Returns the usesGrouping property.
   *
   * @return bool
   */
  function usesGrouping() {
    return $this->usesGrouping;
  }

173 174 175 176 177
  /**
   * Return TRUE if this style also uses fields.
   *
   * @return bool
   */
178
  function usesFields() {
179 180 181
    // If we use a row plugin, ask the row plugin. Chances are, we don't
    // care, it does.
    $row_uses_fields = FALSE;
182 183
    if ($this->usesRowPlugin() && ($row_plugin = $this->displayHandler->getPlugin('row'))) {
      $row_uses_fields = $row_plugin->usesFields();
184 185
    }
    // Otherwise, check the definition or the option.
186
    return $row_uses_fields || $this->usesFields || !empty($this->options['uses_fields']);
187 188 189 190 191 192 193
  }

  /**
   * Return TRUE if this style uses tokens.
   *
   * Used to ensure we don't fetch tokens when not needed for performance.
   */
194
  public function usesTokens() {
195
    if ($this->usesRowClass()) {
196
      $class = $this->options['row_class'];
197
      if (strpos($class, '{{') !== FALSE || strpos($class, '!') !== FALSE || strpos($class, '%') !== FALSE) {
198 199 200 201 202
        return TRUE;
      }
    }
  }

203 204 205 206 207 208 209 210 211
  /**
   * Return TRUE if this style enables field labels by default.
   *
   * @return bool
   */
  public function defaultFieldLabels() {
    return $this->defaultFieldLabels;
  }

212 213 214
  /**
   * Return the token replaced row class for the specified row.
   */
215
  public function getRowClass($row_index) {
216
    if ($this->usesRowClass()) {
217
      $class = $this->options['row_class'];
218
      if ($this->usesFields() && $this->view->field) {
219
        $class = strip_tags($this->tokenizeValue($class, $row_index));
220 221 222 223
      }

      $classes = explode(' ', $class);
      foreach ($classes as &$class) {
224
        $class = Html::cleanCssIdentifier($class);
225 226 227 228 229 230 231 232
      }
      return implode(' ', $classes);
    }
  }

  /**
   * Take a value and apply token replacement logic to it.
   */
233
  public function tokenizeValue($value, $row_index) {
234
    if (strpos($value, '{{') !== FALSE || strpos($value, '!') !== FALSE || strpos($value, '%') !== FALSE) {
235
      // Row tokens might be empty, for example for node row style.
236
      $tokens = isset($this->rowTokens[$row_index]) ? $this->rowTokens[$row_index] : array();
237 238 239 240
      if (!empty($this->view->build_info['substitutions'])) {
        $tokens += $this->view->build_info['substitutions'];
      }

241
      $value = $this->viewsTokenReplace($value, $tokens);
242
    }
243 244 245 246 247
    else {
      // ::viewsTokenReplace() will run Xss::filterAdmin on the
      // resulting string. We do the same here for consistency.
      $value = Xss::filterAdmin($value);
    }
248 249 250 251 252 253
    return $value;
  }

  /**
   * Should the output of the style plugin be rendered even if it's a empty view.
   */
254
  public function evenEmpty() {
255 256 257
    return !empty($this->definition['even empty']);
  }

258 259
  protected function defineOptions() {
    $options = parent::defineOptions();
260
    $options['grouping'] = array('default' => array());
261
    if ($this->usesRowClass()) {
262
      $options['row_class'] = array('default' => '');
263
      $options['default_row_class'] = array('default' => TRUE);
264
    }
265
    $options['uses_fields'] = array('default' => FALSE);
266 267 268 269

    return $options;
  }

270
  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
271
    parent::buildOptionsForm($form, $form_state);
272
    // Only fields-based views can handle grouping.  Style plugins can also exclude
273 274 275 276
    // themselves from being groupable by setting their "usesGrouping" property
    // to FALSE.
    // @TODO: Document "usesGrouping" in docs.php when docs.php is written.
    if ($this->usesFields() && $this->usesGrouping()) {
277
      $options = array('' => $this->t('- None -'));
278
      $field_labels = $this->displayHandler->getFieldLabels(TRUE);
279 280 281
      $options += $field_labels;
      // If there are no fields, we can't group on them.
      if (count($options) > 1) {
282 283
        // This is for backward compatibility, when there was just a single
        // select form.
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
        if (is_string($this->options['grouping'])) {
          $grouping = $this->options['grouping'];
          $this->options['grouping'] = array();
          $this->options['grouping'][0]['field'] = $grouping;
        }
        if (isset($this->options['group_rendered']) && is_string($this->options['group_rendered'])) {
          $this->options['grouping'][0]['rendered'] = $this->options['group_rendered'];
          unset($this->options['group_rendered']);
        }

        $c = count($this->options['grouping']);
        // Add a form for every grouping, plus one.
        for ($i = 0; $i <= $c; $i++) {
          $grouping = !empty($this->options['grouping'][$i]) ? $this->options['grouping'][$i] : array();
          $grouping += array('field' => '', 'rendered' => TRUE, 'rendered_strip' => FALSE);
          $form['grouping'][$i]['field'] = array(
            '#type' => 'select',
301
            '#title' => $this->t('Grouping field Nr.@number', array('@number' => $i + 1)),
302 303
            '#options' => $options,
            '#default_value' => $grouping['field'],
304
            '#description' => $this->t('You may optionally specify a field by which to group the records. Leave blank to not group.'),
305 306 307
          );
          $form['grouping'][$i]['rendered'] = array(
            '#type' => 'checkbox',
308
            '#title' => $this->t('Use rendered output to group rows'),
309
            '#default_value' => $grouping['rendered'],
310
            '#description' => $this->t('If enabled the rendered output of the grouping field is used to group the rows.'),
311 312 313 314 315
            '#states' => array(
              'invisible' => array(
                ':input[name="style_options[grouping][' . $i . '][field]"]' => array('value' => ''),
              ),
            ),
316 317 318
          );
          $form['grouping'][$i]['rendered_strip'] = array(
            '#type' => 'checkbox',
319
            '#title' => $this->t('Remove tags from rendered output'),
320
            '#default_value' => $grouping['rendered_strip'],
321 322 323 324 325
            '#states' => array(
              'invisible' => array(
                ':input[name="style_options[grouping][' . $i . '][field]"]' => array('value' => ''),
              ),
            ),
326 327 328 329 330
          );
        }
      }
    }

331
    if ($this->usesRowClass()) {
332
      $form['row_class'] = array(
333 334
        '#title' => $this->t('Row class'),
        '#description' => $this->t('The class to provide on each row.'),
335 336 337 338
        '#type' => 'textfield',
        '#default_value' => $this->options['row_class'],
      );

339
      if ($this->usesFields()) {
340
        $form['row_class']['#description'] .= ' ' . $this->t('You may use field tokens from as per the "Replacement patterns" used in "Rewrite the output of this field" for all fields.');
341 342 343
      }

      $form['default_row_class'] = array(
344 345
        '#title' => $this->t('Add views row classes'),
        '#description' => $this->t('Add the default row classes like views-row-1 to the output. You can use this to quickly reduce the amount of markup the view provides by default, at the cost of making it more difficult to apply CSS.'),
346 347 348 349 350
        '#type' => 'checkbox',
        '#default_value' => $this->options['default_row_class'],
      );
    }

351
    if (!$this->usesFields() || !empty($this->options['uses_fields'])) {
352 353
      $form['uses_fields'] = array(
        '#type' => 'checkbox',
354 355
        '#title' => $this->t('Force using fields'),
        '#description' => $this->t('If neither the row nor the style plugin supports fields, this field allows to enable them, so you can for example use groupby.'),
356 357 358 359 360
        '#default_value' => $this->options['uses_fields'],
      );
    }
  }

361
  public function validateOptionsForm(&$form, FormStateInterface $form_state) {
362
    // Don't run validation on style plugins without the grouping setting.
363
    if ($form_state->hasValue(array('style_options', 'grouping'))) {
364
      // Don't save grouping if no field is specified.
365 366
      $groupings = $form_state->getValue(array('style_options', 'grouping'));
      foreach ($groupings as $index => $grouping) {
367
        if (empty($grouping['field'])) {
368
          $form_state->unsetValue(array('style_options', 'grouping', $index));
369 370 371 372 373
        }
      }
    }
  }

374 375 376 377 378
  /**
   * Provide a form in the views wizard if this style is selected.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
379 380
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
381 382 383
   * @param string $type
   *    The display type, either block or page.
   */
384
  public function wizardForm(&$form, FormStateInterface $form_state, $type) {
385 386 387 388 389 390 391
  }

  /**
   * Alter the options of a display before they are added to the view.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
392 393
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
394
   * @param \Drupal\views\Plugin\views\wizard\WizardInterface $wizard
395 396 397 398 399 400 401
   *   The current used wizard.
   * @param array $display_options
   *   The options which will be used on the view. The style plugin should
   *   alter this to its own needs.
   * @param string $display_type
   *   The display type, either block or page.
   */
402
  public function wizardSubmit(&$form, FormStateInterface $form_state, WizardInterface $wizard, &$display_options, $display_type) {
403 404
  }

405 406 407 408 409
  /**
   * Called by the view builder to see if this style handler wants to
   * interfere with the sorts. If so it should build; if it returns
   * any non-TRUE value, normal sorting will NOT be added to the query.
   */
410
  public function buildSort() { return TRUE; }
411 412 413 414 415

  /**
   * Called by the view builder to let the style build a second set of
   * sorts that will come after any other sorts in the view.
   */
416
  public function buildSortPost() { }
417 418 419 420 421 422 423

  /**
   * Allow the style to do stuff before each row is rendered.
   *
   * @param $result
   *   The full array of results from the query.
   */
424
  public function preRender($result) {
425
    if (!empty($this->view->rowPlugin)) {
426
      $this->view->rowPlugin->preRender($result);
427 428 429
    }
  }

430
  /**
431 432 433 434
   * Renders a group of rows of the grouped view.
   *
   * @param array $rows
   *   The result rows rendered in this group.
435 436
   *
   * @return array
437
   *   The render array containing the single group theme output.
438
   */
439
  protected function renderRowGroup(array $rows = array()) {
440 441 442 443 444 445 446
    return array(
      '#theme' => $this->themeFunctions(),
      '#view' => $this->view,
      '#rows' => $rows,
    );
  }

447 448 449
  /**
   * Render the display in this style.
   */
450
  public function render() {
451
    if ($this->usesRowPlugin() && empty($this->view->rowPlugin)) {
452
      debug('Drupal\views\Plugin\views\style\StylePluginBase: Missing row plugin');
453 454 455 456
      return;
    }

    // Group the rows according to the grouping instructions, if specified.
457
    $sets = $this->renderGrouping(
458 459 460 461 462
      $this->view->result,
      $this->options['grouping'],
      TRUE
    );

463
    return $this->renderGroupingSets($sets);
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
  }

  /**
   * Render the grouping sets.
   *
   * Plugins may override this method if they wish some other way of handling
   * grouping.
   *
   * @param $sets
   *   Array containing the grouping sets to render.
   * @param $level
   *   Integer indicating the hierarchical level of the grouping.
   *
   * @return string
   *   Rendered output of given grouping sets.
   */
480
  public function renderGroupingSets($sets, $level = 0) {
481
    $output = array();
482
    $theme_functions = $this->view->buildThemeFunctions($this->groupingTheme);
483 484 485 486
    foreach ($sets as $set) {
      $row = reset($set['rows']);
      // Render as a grouping set.
      if (is_array($row) && isset($row['group'])) {
487 488 489 490 491 492 493
        $output[] = array(
          '#theme' => $theme_functions,
          '#view' => $this->view,
          '#grouping' => $this->options['grouping'][$level],
          '#grouping_level' => $level,
          '#rows' => $set['rows'],
          '#title' => $set['group'],
494 495 496 497
        );
      }
      // Render as a record set.
      else {
498
        if ($this->usesRowPlugin()) {
499 500
          foreach ($set['rows'] as $index => $row) {
            $this->view->row_index = $index;
501
            $set['rows'][$index] = $this->view->rowPlugin->render($row);
502 503 504
          }
        }

505
        $single_output = $this->renderRowGroup($set['rows']);
506 507 508
        $single_output['#grouping_level'] = $level;
        $single_output['#title'] = $set['group'];
        $output[] = $single_output;
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
      }
    }
    unset($this->view->row_index);
    return $output;
  }

  /**
   * Group records as needed for rendering.
   *
   * @param $records
   *   An array of records from the view to group.
   * @param $groupings
   *   An array of grouping instructions on which fields to group. If empty, the
   *   result set will be given a single group with an empty string as a label.
   * @param $group_rendered
   *   Boolean value whether to use the rendered or the raw field value for
   *   grouping. If set to NULL the return is structured as before
   *   Views 7.x-3.0-rc2. After Views 7.x-3.0 this boolean is only used if
   *   $groupings is an old-style string or if the rendered option is missing
   *   for a grouping instruction.
   * @return
   *   The grouped record set.
   *   A nested set structure is generated if multiple grouping fields are used.
   *
   *   @code
   *   array(
   *     'grouping_field_1:grouping_1' => array(
   *       'group' => 'grouping_field_1:content_1',
   *       'rows' => array(
   *         'grouping_field_2:grouping_a' => array(
   *           'group' => 'grouping_field_2:content_a',
   *           'rows' => array(
   *             $row_index_1 => $row_1,
   *             $row_index_2 => $row_2,
   *             // ...
   *           )
   *         ),
   *       ),
   *     ),
   *     'grouping_field_1:grouping_2' => array(
   *       // ...
   *     ),
   *   )
   *   @endcode
   */
554
  public function renderGrouping($records, $groupings = array(), $group_rendered = NULL) {
555 556
    // This is for backward compatibility, when $groupings was a string
    // containing the ID of a single field.
557 558 559 560 561 562
    if (is_string($groupings)) {
      $rendered = $group_rendered === NULL ? TRUE : $group_rendered;
      $groupings = array(array('field' => $groupings, 'rendered' => $rendered));
    }

    // Make sure fields are rendered
563
    $this->renderFields($this->view->result);
564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580
    $sets = array();
    if ($groupings) {
      foreach ($records as $index => $row) {
        // Iterate through configured grouping fields to determine the
        // hierarchically positioned set where the current row belongs to.
        // While iterating, parent groups, that do not exist yet, are added.
        $set = &$sets;
        foreach ($groupings as $info) {
          $field = $info['field'];
          $rendered = isset($info['rendered']) ? $info['rendered'] : $group_rendered;
          $rendered_strip = isset($info['rendered_strip']) ? $info['rendered_strip'] : FALSE;
          $grouping = '';
          $group_content = '';
          // Group on the rendered version of the field, not the raw.  That way,
          // we can control any special formatting of the grouping field through
          // the admin or theme layer or anywhere else we'd like.
          if (isset($this->view->field[$field])) {
581
            $group_content = $this->getField($index, $field);
582 583 584 585 586 587 588 589 590 591
            if ($this->view->field[$field]->options['label']) {
              $group_content = $this->view->field[$field]->options['label'] . ': ' . $group_content;
            }
            if ($rendered) {
              $grouping = $group_content;
              if ($rendered_strip) {
                $group_content = $grouping = strip_tags(htmlspecialchars_decode($group_content));
              }
            }
            else {
592
              $grouping = $this->getFieldValue($index, $field);
593 594 595
              // Not all field handlers return a scalar value,
              // e.g. views_handler_field_field.
              if (!is_scalar($grouping)) {
596
                $grouping = hash('sha256', serialize($grouping));
597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621
              }
            }
          }

          // Create the group if it does not exist yet.
          if (empty($set[$grouping])) {
            $set[$grouping]['group'] = $group_content;
            $set[$grouping]['rows'] = array();
          }

          // Move the set reference into the row set of the group we just determined.
          $set = &$set[$grouping]['rows'];
        }
        // Add the row to the hierarchically positioned row set we just determined.
        $set[$index] = $row;
      }
    }
    else {
      // Create a single group with an empty grouping field.
      $sets[''] = array(
        'group' => '',
        'rows' => $records,
      );
    }

622
    // If this parameter isn't explicitly set, modify the output to be fully
623 624 625 626 627 628 629 630 631 632 633 634 635 636
    // backward compatible to code before Views 7.x-3.0-rc2.
    // @TODO Remove this as soon as possible e.g. October 2020
    if ($group_rendered === NULL) {
      $old_style_sets = array();
      foreach ($sets as $group) {
        $old_style_sets[$group['group']] = $group['rows'];
      }
      $sets = $old_style_sets;
    }

    return $sets;
  }

  /**
637
   * Renders all of the fields for a given style and store them on the object.
638
   *
639
   * @param array $result
640 641
   *   The result array from $view->result
   */
642
  protected function renderFields(array $result) {
643
    if (!$this->usesFields()) {
644 645 646 647
      return;
    }

    if (!isset($this->rendered_fields)) {
648
      $this->rendered_fields = [];
649
      $this->view->row_index = 0;
650 651 652 653 654 655
      $field_ids = array_keys($this->view->field);

      // Only tokens relating to field handlers preceding the one we invoke
      // ::getRenderTokens() on are returned, so here we need to pick the last
      // available field handler.
      $render_tokens_field_id = end($field_ids);
656 657 658

      // If all fields have a field::access FALSE there might be no fields, so
      // there is no reason to execute this code.
659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686
      if (!empty($field_ids)) {
        $renderer = $this->getRenderer();
        /** @var \Drupal\views\Plugin\views\cache\CachePluginBase $cache_plugin */
        $cache_plugin = $this->view->display_handler->getPlugin('cache');

        /** @var \Drupal\views\ResultRow $row */
        foreach ($result as $index => $row) {
          $this->view->row_index = $index;

          // Here we implement render caching for result rows. Since we never
          // build a render array for single rows, given that style templates
          // need individual field markup to support proper theming, we build
          // a raw render array containing all field render arrays and cache it.
          // This allows us to cache the markup of the various children, that is
          // individual fields, which is then available for style template
          // preprocess functions, later in the rendering workflow.
          // @todo Fetch all the available cached row items in one single cache
          //   get operation, once https://www.drupal.org/node/2453945 is fixed.
          $data = [
            '#pre_render' => [[$this, 'elementPreRenderRow']],
            '#row' => $row,
            '#cache' => [
              'keys' => $cache_plugin->getRowCacheKeys($row),
              'tags' => $cache_plugin->getRowCacheTags($row),
            ],
            '#cache_properties' => $field_ids,
          ];
          $renderer->addCacheableDependency($data, $this->view->storage);
687
          $renderer->renderPlain($data);
688 689 690 691 692 693 694 695 696 697 698

          // Extract field output from the render array and post process it.
          $fields = $this->view->field;
          $rendered_fields = &$this->rendered_fields[$index];
          $post_render_tokens = [];
          foreach ($field_ids as $id)  {
            $rendered_fields[$id] = $data[$id]['#markup'];
            $tokens = $fields[$id]->postRender($row, $rendered_fields[$id]);
            if ($tokens) {
              $post_render_tokens += $tokens;
            }
699 700
          }

701 702 703 704 705 706 707 708
          // Populate row tokens.
          $this->rowTokens[$index] = $this->view->field[$render_tokens_field_id]->getRenderTokens([]);

          // Replace post-render tokens.
          if ($post_render_tokens) {
            $placeholders = array_keys($post_render_tokens);
            $values = array_values($post_render_tokens);
            foreach ($this->rendered_fields[$index] as &$rendered_field) {
709 710 711
              // Placeholders and rendered fields have been processed by the
              // render system and are therefore safe.
              $rendered_field = SafeString::create(str_replace($placeholders, $values, $rendered_field));
712 713
            }
          }
714 715
        }
      }
716

717 718 719 720
      unset($this->view->row_index);
    }
  }

721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
  /**
   * #pre_render callback for view row field rendering.
   *
   * @see self::render()
   *
   * @param array $data
   *   The element to #pre_render
   *
   * @return array
   *   The processed element.
   */
  public function elementPreRenderRow(array $data) {
    // Render row fields.
    foreach ($this->view->field as $id => $field) {
      $data[$id] = ['#markup' => $field->theme($data['#row'])];
    }
    return $data;
  }

740
  /**
741
   * Gets a rendered field.
742
   *
743
   * @param int $index
744
   *   The index count of the row.
745 746 747
   * @param string $field
   *   The ID of the field.
   *
748
   * @return \Drupal\Core\Render\SafeString|null
749
   *   The output of the field, or NULL if it was empty.
750
   */
751
  public function getField($index, $field) {
752
    if (!isset($this->rendered_fields)) {
753
      $this->renderFields($this->view->result);
754 755 756 757 758 759 760 761
    }

    if (isset($this->rendered_fields[$index][$field])) {
      return $this->rendered_fields[$index][$field];
    }
  }

  /**
762 763 764 765 766 767 768
   * Get the raw field value.
   *
   * @param $index
   *   The index count of the row.
   * @param $field
   *    The id of the field.
   */
769
  public function getFieldValue($index, $field) {
770
    $this->view->row_index = $index;
771
    $value = $this->view->field[$field]->getValue($this->view->result[$index]);
772 773 774 775
    unset($this->view->row_index);
    return $value;
  }

776
  public function validate() {
777 778
    $errors = parent::validate();

779
    if ($this->usesRowPlugin()) {
780
      $plugin = $this->displayHandler->getPlugin('row');
781
      if (empty($plugin)) {
782
        $errors[] = $this->t('Style @style requires a row style but the row plugin is invalid.', array('@style' => $this->definition['title']));
783 784 785 786 787 788 789 790 791 792 793
      }
      else {
        $result = $plugin->validate();
        if (!empty($result) && is_array($result)) {
          $errors = array_merge($errors, $result);
        }
      }
    }
    return $errors;
  }

794
  public function query() {
795
    parent::query();
796 797
    if (isset($this->view->rowPlugin)) {
      $this->view->rowPlugin->query();
798 799
    }
  }
800

801 802 803 804 805
}

/**
 * @}
 */