Field.php 34.5 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Contains \Drupal\views\Plugin\views\field\Field.
6 7
 */

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

10
use Drupal\Component\Utility\Xss;
11 12
use Drupal\Core\Cache\Cache;
use Drupal\Core\Cache\CacheableDependencyInterface;
13
use Drupal\Core\Entity\EntityInterface;
14
use Drupal\Core\Entity\EntityManagerInterface;
15
use Drupal\Core\Field\FieldStorageDefinitionInterface;
16
use Drupal\Core\Field\FieldTypePluginManagerInterface;
17
use Drupal\Core\Field\FormatterPluginManager;
18
use Drupal\Core\Form\FormHelper;
19
use Drupal\Core\Form\FormStateInterface;
20
use Drupal\Core\Language\LanguageManagerInterface;
21
use Drupal\Core\Render\BubbleableMetadata;
22
use Drupal\Core\Render\Element;
23
use Drupal\Core\Render\RendererInterface;
24
use Drupal\Core\Session\AccountInterface;
25
use Drupal\views\FieldAPIHandlerTrait;
26
use Drupal\views\Entity\Render\EntityFieldRenderer;
27
use Drupal\views\Plugin\views\display\DisplayPluginBase;
28
use Drupal\views\ResultRow;
29
use Drupal\views\ViewExecutable;
30
use Symfony\Component\DependencyInjection\ContainerInterface;
31 32

/**
33
 * A field that displays entity field data.
34 35
 *
 * @ingroup views_field_handlers
36
 *
37 38
 * @todo Rename the class https://www.drupal.org/node/2408667
 *
39
 * @ViewsField("field")
40
 */
41
class Field extends FieldPluginBase implements CacheableDependencyInterface, MultiItemsFieldHandlerInterface {
42 43
  use FieldAPIHandlerTrait;

44
  /**
45
   * An array to store field renderable arrays for use by renderItems().
46
   *
47 48 49 50 51 52
   * @var array
   */
  public $items = array();

  /**
   * Does the field supports multiple field values.
53
   *
54 55 56 57 58 59
   * @var bool
   */
  public $multiple;

  /**
   * Does the rendered fields get limited.
60
   *
61 62 63 64 65 66
   * @var bool
   */
  public $limit_values;

  /**
   * A shortcut for $view->base_table.
67
   *
68 69 70 71
   * @var string
   */
  public $base_table;

72 73 74 75 76 77 78
  /**
   * An array of formatter options.
   *
   * @var array
   */
  protected $formatterOptions;

79 80 81
  /**
   * The entity manager.
   *
82
   * @var \Drupal\Core\Entity\EntityManagerInterface
83 84 85
   */
  protected $entityManager;

86 87 88
  /**
   * The field formatter plugin manager.
   *
89
   * @var \Drupal\Core\Field\FormatterPluginManager
90 91 92
   */
  protected $formatterPluginManager;

93 94 95
  /**
   * The language manager.
   *
96
   * @var \Drupal\Core\Language\LanguageManagerInterface
97 98 99
   */
  protected $languageManager;

100 101 102 103 104 105 106
  /**
   * The renderer.
   *
   * @var \Drupal\Core\Render\RendererInterface
   */
  protected $renderer;

107 108 109 110 111 112 113
  /**
   * The field type plugin manager.
   *
   * @var \Drupal\Core\Field\FieldTypePluginManagerInterface
   */
  protected $fieldTypePluginManager;

114 115 116 117 118 119 120
  /**
   * Static cache for ::getEntityFieldRenderer().
   *
   * @var \Drupal\views\Entity\Render\EntityFieldRenderer
   */
  protected $entityFieldRenderer;

121 122 123 124 125 126 127
  /**
   * Constructs a \Drupal\field\Plugin\views\field\Field object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
128
   * @param mixed $plugin_definition
129
   *   The plugin implementation definition.
130
   * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
131
   *   The field formatter plugin manager.
132
   * @param \Drupal\Core\Field\FormatterPluginManager $formatter_plugin_manager
133
   *   The field formatter plugin manager.
134 135
   * @param \Drupal\Core\Field\FieldTypePluginManagerInterface $field_type_plugin_manager
   *   The field plugin type manager.
136
   * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
137
   *   The language manager.
138 139
   * @param \Drupal\Core\Render\RendererInterface $renderer
   *   The renderer.
140
   */
141
  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityManagerInterface $entity_manager, FormatterPluginManager $formatter_plugin_manager, FieldTypePluginManagerInterface $field_type_plugin_manager, LanguageManagerInterface $language_manager, RendererInterface $renderer) {
142 143
    parent::__construct($configuration, $plugin_id, $plugin_definition);

144
    $this->entityManager = $entity_manager;
145
    $this->formatterPluginManager = $formatter_plugin_manager;
146
    $this->fieldTypePluginManager = $field_type_plugin_manager;
147
    $this->languageManager = $language_manager;
148
    $this->renderer = $renderer;
149 150 151 152 153 154

    // @todo Unify 'entity field'/'field_name' instead of converting back and
    //   forth. https://www.drupal.org/node/2410779
    if (isset($this->definition['entity field'])) {
      $this->definition['field_name'] = $this->definition['entity field'];
    }
155 156 157 158 159
  }

  /**
   * {@inheritdoc}
   */
160
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
161 162 163 164
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
165
      $container->get('entity.manager'),
166
      $container->get('plugin.manager.field.formatter'),
167
      $container->get('plugin.manager.field.field_type'),
168 169
      $container->get('language_manager'),
      $container->get('renderer')
170 171 172
    );
  }

173
  /**
174
   * {@inheritdoc}
175 176 177
   */
  public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
    parent::init($view, $display, $options);
178 179 180 181

    $this->multiple = FALSE;
    $this->limit_values = FALSE;

182
    $field_definition = $this->getFieldDefinition();
183 184
    $cardinality = $field_definition->getFieldStorageDefinition()->getCardinality();
    if ($field_definition->getFieldStorageDefinition()->isMultiple()) {
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
      $this->multiple = TRUE;

      // If "Display all values in the same row" is FALSE, then we always limit
      // in order to show a single unique value per row.
      if (!$this->options['group_rows']) {
        $this->limit_values = TRUE;
      }

      // If "First and last only" is chosen, limit the values
      if (!empty($this->options['delta_first_last'])) {
        $this->limit_values = TRUE;
      }

      // Otherwise, we only limit values if the user hasn't selected "all", 0, or
      // the value matching field cardinality.
200
      if ((($this->options['delta_limit'] > 0) && ($this->options['delta_limit'] != $cardinality)) || intval($this->options['delta_offset'])) {
201 202 203 204 205
        $this->limit_values = TRUE;
      }
    }
  }

206 207 208 209 210 211 212
  /**
   * {@inheritdoc}
   */
  protected function getEntityManager() {
    return $this->entityManager;
  }

213
  /**
214
   * {@inheritdoc}
215
   */
216
  public function access(AccountInterface $account) {
217
    $access_control_handler = $this->entityManager->getAccessControlHandler($this->getEntityType());
218
    return $access_control_handler->fieldAccess('view', $this->getFieldDefinition(), $account);
219 220 221 222 223
  }

  /**
   * Called to add the field to a query.
   *
224 225
   * By default, all needed data is taken from entities loaded by the query
   * plugin. Columns are added only if they are used in groupings.
226
   */
227
  public function query($use_groupby = FALSE) {
228
    $fields = $this->additional_fields;
229
    // No need to add the entity type.
230 231 232 233 234 235 236 237 238 239 240 241 242 243
    $entity_type_key = array_search('entity_type', $fields);
    if ($entity_type_key !== FALSE) {
      unset($fields[$entity_type_key]);
    }

    if ($use_groupby) {
      // Add the fields that we're actually grouping on.
      $options = array();
      if ($this->options['group_column'] != 'entity_id') {
        $options = array($this->options['group_column'] => $this->options['group_column']);
      }
      $options += is_array($this->options['group_columns']) ? $this->options['group_columns'] : array();

      // Go through the list and determine the actual column name from field api.
244
      $fields = array();
245 246 247
      $table_mapping = $this->getTableMapping();
      $field_definition = $this->getFieldStorageDefinition();

248
      foreach ($options as $column) {
249
        $fields[$column] = $table_mapping->getFieldColumnName($field_definition, $column);
250 251 252 253 254 255 256
      }

      $this->group_fields = $fields;
    }

    // Add additional fields (and the table join itself) if needed.
    if ($this->add_field_table($use_groupby)) {
257
      $this->ensureMyTable();
258
      $this->addAdditionalFields($fields);
259
    }
260

261 262
    // Let the entity field renderer alter the query if needed.
    $this->getEntityFieldRenderer()->query($this->query, $this->relationship);
263 264 265 266 267 268
  }

  /**
   * Determine if the field table should be added to the query.
   */
  function add_field_table($use_groupby) {
269 270
    // Grouping is enabled.
    if ($use_groupby) {
271 272 273 274 275 276 277 278 279 280
      return TRUE;
    }
    // This a multiple value field, but "group multiple values" is not checked.
    if ($this->multiple && !$this->options['group_rows']) {
      return TRUE;
    }
    return FALSE;
  }

  /**
281
   * {@inheritdoc}
282
   */
283
  public function clickSortable() {
284 285 286 287 288 289
    // A field is not click sortable if it's a multiple field with
    // "group multiple values" checked, since a click sort in that case would
    // add a join to the field table, which would produce unwanted duplicates.
    if ($this->multiple && $this->options['group_rows']) {
      return FALSE;
    }
290 291 292 293 294 295 296

    // If field definition is set, use that.
    if (isset($this->definition['click sortable'])) {
      return (bool) $this->definition['click sortable'];
    }

    // Default to true.
297 298 299 300 301 302
    return TRUE;
  }

  /**
   * Called to determine what to tell the clicksorter.
   */
303
  public function clickSort($order) {
304 305 306 307 308
    // No column selected, can't continue.
    if (empty($this->options['click_sort_column'])) {
      return;
    }

309
    $this->ensureMyTable();
310 311
    $field_storage_definition = $this->getFieldStorageDefinition();
    $column = $this->getTableMapping()->getFieldColumnName($field_storage_definition, $this->options['click_sort_column']);
312 313
    if (!isset($this->aliases[$column])) {
      // Column is not in query; add a sort on it (without adding the column).
314
      $this->aliases[$column] = $this->tableAlias . '.' . $column;
315
    }
316
    $this->query->addOrderBy(NULL, NULL, $order, $this->aliases[$column]);
317 318
  }

319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
  /**
   * Gets the field storage of the used field.
   *
   * @return \Drupal\Core\Field\FieldStorageDefinitionInterface
   */
  protected function getFieldStorageDefinition() {
    $entity_type_id = $this->definition['entity_type'];
    $field_storage_definitions = $this->entityManager->getFieldStorageDefinitions($entity_type_id);

    $field_storage = NULL;
    // @todo Unify 'entity field'/'field_name' instead of converting back and
    //   forth. https://www.drupal.org/node/2410779
    if (isset($this->definition['field_name'])) {
      $field_storage = $field_storage_definitions[$this->definition['field_name']];
    }
    elseif (isset($this->definition['entity field'])) {
      $field_storage = $field_storage_definitions[$this->definition['entity field']];
    }
    return $field_storage;
  }

  /**
   * {@inheritdoc}
   */
343 344
  protected function defineOptions() {
    $options = parent::defineOptions();
345

346 347 348
    $field_storage_definition = $this->getFieldStorageDefinition();
    $field_type = $this->fieldTypePluginManager->getDefinition($field_storage_definition->getType());
    $column_names = array_keys($field_storage_definition->getColumns());
349 350 351 352 353 354 355 356 357 358 359 360 361
    $default_column = '';
    // Try to determine a sensible default.
    if (count($column_names) == 1) {
      $default_column = $column_names[0];
    }
    elseif (in_array('value', $column_names)) {
      $default_column = 'value';
    }

    // If the field has a "value" column, we probably need that one.
    $options['click_sort_column'] = array(
      'default' => $default_column,
    );
362

363 364 365 366 367 368 369 370 371
    if (isset($this->definition['default_formatter'])) {
      $options['type'] = ['default' => $this->definition['default_formatter']];
    }
    elseif (isset($field_type['default_formatter'])) {
      $options['type'] = ['default' => $field_type['default_formatter']];
    }
    else {
      $options['type'] = ['default' => ''];
    }
372

373
    $options['settings'] = array(
374
      'default' => isset($this->definition['default_formatter_settings']) ? $this->definition['default_formatter_settings'] : [],
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
    );
    $options['group_column'] = array(
      'default' => $default_column,
    );
    $options['group_columns'] = array(
      'default' => array(),
    );

    // Options used for multiple value fields.
    $options['group_rows'] = array(
      'default' => TRUE,
    );
    // If we know the exact number of allowed values, then that can be
    // the default. Otherwise, default to 'all'.
    $options['delta_limit'] = array(
390
      'default' => ($field_storage_definition->getCardinality() > 1) ? $field_storage_definition->getCardinality() : 0,
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
    );
    $options['delta_offset'] = array(
      'default' => 0,
    );
    $options['delta_reversed'] = array(
      'default' => FALSE,
    );
    $options['delta_first_last'] = array(
      'default' => FALSE,
    );

    $options['multi_type'] = array(
      'default' => 'separator'
    );
    $options['separator'] = array(
      'default' => ', '
    );

    $options['field_api_classes'] = array(
      'default' => FALSE,
    );

    return $options;
  }

416 417 418
  /**
   * {@inheritdoc}
   */
419
  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
420
    parent::buildOptionsForm($form, $form_state);
421

422
    $field = $this->getFieldDefinition();
423
    $formatters = $this->formatterPluginManager->getOptions($field->getType());
424
    $column_names = array_keys($field->getColumns());
425 426 427 428 429 430 431

    // If this is a multiple value field, add its options.
    if ($this->multiple) {
      $this->multiple_options_form($form, $form_state);
    }

    // No need to ask the user anything if the field has only one column.
432
    if (count($field->getColumns()) == 1) {
433 434 435 436 437 438 439 440
      $form['click_sort_column'] = array(
        '#type' => 'value',
        '#value' => isset($column_names[0]) ? $column_names[0] : '',
      );
    }
    else {
      $form['click_sort_column'] = array(
        '#type' => 'select',
441
        '#title' => $this->t('Column used for click sorting'),
442
        '#options' => array_combine($column_names, $column_names),
443
        '#default_value' => $this->options['click_sort_column'],
444
        '#description' => $this->t('Used by Style: Table to determine the actual column to click sort the field on. The default is usually fine.'),
445 446 447 448 449
      );
    }

    $form['type'] = array(
      '#type' => 'select',
450
      '#title' => $this->t('Formatter'),
451 452 453
      '#options' => $formatters,
      '#default_value' => $this->options['type'],
      '#ajax' => array(
454
        'url' => views_ui_build_form_url($form_state),
455
      ),
456
      '#submit' => array(array($this, 'submitTemporaryForm')),
457 458 459 460
      '#executes_submit_callback' => TRUE,
    );

    $form['field_api_classes'] = array(
461
      '#title' => $this->t('Use field template'),
462 463
      '#type' => 'checkbox',
      '#default_value' => $this->options['field_api_classes'],
464
      '#description' => $this->t('If checked, field api classes will be added by field templates. This is not recommended unless your CSS depends upon these classes. If not checked, template will not be used.'),
465 466 467 468 469
      '#fieldset' => 'style_settings',
      '#weight' => 20,
    );

    if ($this->multiple) {
470
      $form['field_api_classes']['#description'] .= ' ' . $this->t('Checking this option will cause the group Display Type and Separator values to be ignored.');
471 472 473 474 475
    }

    // Get the currently selected formatter.
    $format = $this->options['type'];

476
    $settings = $this->options['settings'] + $this->formatterPluginManager->getDefaultSettings($format);
477

478
    $options = array(
479
      'field_definition' => $field,
480 481 482 483 484 485 486 487 488
      'configuration' => array(
        'type' => $format,
        'settings' => $settings,
        'label' => '',
        'weight' => 0,
      ),
      'view_mode' => '_custom',
    );

489 490
    // Get the settings form.
    $settings_form = array('#value' => array());
491
    if ($formatter = $this->formatterPluginManager->getInstance($options)) {
492
      $settings_form = $formatter->settingsForm($form, $form_state);
493 494
      // Convert field UI selector states to work in the Views field form.
      FormHelper::rewriteStatesSelector($settings_form, "fields[{$field->getName()}][settings_edit_form]", 'options');
495 496 497 498 499 500 501
    }
    $form['settings'] = $settings_form;
  }

  /**
   * Provide options for multiple value fields.
   */
502
  function multiple_options_form(&$form, FormStateInterface $form_state) {
503
    $field = $this->getFieldDefinition();
504 505

    $form['multiple_field_settings'] = array(
506
      '#type' => 'details',
507
      '#title' => $this->t('Multiple field settings'),
508 509 510 511
      '#weight' => 5,
    );

    $form['group_rows'] = array(
512
      '#title' => $this->t('Display all values in the same row'),
513 514
      '#type' => 'checkbox',
      '#default_value' => $this->options['group_rows'],
515
      '#description' => $this->t('If checked, multiple values for this field will be shown in the same row. If not checked, each value in this field will create a new row. If using group by, please make sure to group by "Entity ID" for this setting to have any effect.'),
516 517 518 519 520
      '#fieldset' => 'multiple_field_settings',
    );

    // Make the string translatable by keeping it as a whole rather than
    // translating prefix and suffix separately.
521
    list($prefix, $suffix) = explode('@count', $this->t('Display @count value(s)'));
522

523
    if ($field->getCardinality() == FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED) {
524 525 526 527 528 529
      $type = 'textfield';
      $options = NULL;
      $size = 5;
    }
    else {
      $type = 'select';
530 531
      $range = range(1, $field->getCardinality());
      $options = array_combine($range, $range);
532 533 534 535
      $size = 1;
    }
    $form['multi_type'] = array(
      '#type' => 'radios',
536
      '#title' => $this->t('Display type'),
537
      '#options' => array(
538 539 540
        'ul' => $this->t('Unordered list'),
        'ol' => $this->t('Ordered list'),
        'separator' => $this->t('Simple separator'),
541 542 543 544 545 546 547 548 549 550 551 552
      ),
      '#states' => array(
        'visible' => array(
          ':input[name="options[group_rows]"]' => array('checked' => TRUE),
        ),
      ),
      '#default_value' => $this->options['multi_type'],
      '#fieldset' => 'multiple_field_settings',
    );

    $form['separator'] = array(
      '#type' => 'textfield',
553
      '#title' => $this->t('Separator'),
554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579
      '#default_value' => $this->options['separator'],
      '#states' => array(
        'visible' => array(
          ':input[name="options[group_rows]"]' => array('checked' => TRUE),
          ':input[name="options[multi_type]"]' => array('value' => 'separator'),
        ),
      ),
      '#fieldset' => 'multiple_field_settings',
    );

    $form['delta_limit'] = array(
      '#type' => $type,
      '#size' => $size,
      '#field_prefix' => $prefix,
      '#field_suffix' => $suffix,
      '#options' => $options,
      '#default_value' => $this->options['delta_limit'],
      '#prefix' => '<div class="container-inline">',
      '#states' => array(
        'visible' => array(
          ':input[name="options[group_rows]"]' => array('checked' => TRUE),
        ),
      ),
      '#fieldset' => 'multiple_field_settings',
    );

580
    list($prefix, $suffix) = explode('@count', $this->t('starting from @count'));
581 582 583 584 585 586 587 588 589 590 591
    $form['delta_offset'] = array(
      '#type' => 'textfield',
      '#size' => 5,
      '#field_prefix' => $prefix,
      '#field_suffix' => $suffix,
      '#default_value' => $this->options['delta_offset'],
      '#states' => array(
        'visible' => array(
          ':input[name="options[group_rows]"]' => array('checked' => TRUE),
        ),
      ),
592
      '#description' => $this->t('(first item is 0)'),
593 594 595
      '#fieldset' => 'multiple_field_settings',
    );
    $form['delta_reversed'] = array(
596
      '#title' => $this->t('Reversed'),
597 598 599 600 601 602 603 604
      '#type' => 'checkbox',
      '#default_value' => $this->options['delta_reversed'],
      '#suffix' => $suffix,
      '#states' => array(
        'visible' => array(
          ':input[name="options[group_rows]"]' => array('checked' => TRUE),
        ),
      ),
605
      '#description' => $this->t('(start from last values)'),
606 607 608
      '#fieldset' => 'multiple_field_settings',
    );
    $form['delta_first_last'] = array(
609
      '#title' => $this->t('First and last only'),
610 611 612 613 614 615 616 617 618 619 620 621 622 623 624
      '#type' => 'checkbox',
      '#default_value' => $this->options['delta_first_last'],
      '#suffix' => '</div>',
      '#states' => array(
        'visible' => array(
          ':input[name="options[group_rows]"]' => array('checked' => TRUE),
        ),
      ),
      '#fieldset' => 'multiple_field_settings',
    );
  }

  /**
   * Extend the groupby form with group columns.
   */
625
  public function buildGroupByForm(&$form, FormStateInterface $form_state) {
626
    parent::buildGroupByForm($form, $form_state);
627 628
    // With "field API" fields, the column target of the grouping function
    // and any additional grouping columns must be specified.
629

630
    $field_columns = array_keys($this->getFieldDefinition()->getColumns());
631
    $group_columns = array(
632
      'entity_id' => $this->t('Entity ID'),
633
    ) + array_map('ucfirst', array_combine($field_columns, $field_columns));
634 635 636

    $form['group_column'] = array(
      '#type' => 'select',
637
      '#title' => $this->t('Group column'),
638
      '#default_value' => $this->options['group_column'],
639
      '#description' => $this->t('Select the column of this field to apply the grouping function selected above.'),
640 641 642
      '#options' => $group_columns,
    );

643 644 645 646 647
    $options = array(
      'bundle' => 'Bundle',
      'language' => 'Language',
      'entity_type' => 'Entity_type',
    );
648 649 650
    // Add on defined fields, noting that they're prefixed with the field name.
    $form['group_columns'] = array(
      '#type' => 'checkboxes',
651
      '#title' => $this->t('Group columns (additional)'),
652
      '#default_value' => $this->options['group_columns'],
653
      '#description' => $this->t('Select any additional columns of this field to include in the query and to group on.'),
654 655 656 657
      '#options' => $options + $group_columns,
    );
  }

658
  public function submitGroupByForm(&$form, FormStateInterface $form_state) {
659
    parent::submitGroupByForm($form, $form_state);
660
    $item = &$form_state->get('handler')->options;
661 662

    // Add settings for "field API" fields.
663 664
    $item['group_column'] = $form_state->getValue(array('options', 'group_column'));
    $item['group_columns'] = array_filter($form_state->getValue(array('options', 'group_columns')));
665 666 667 668 669 670 671 672
  }

  /**
   * Render all items in this field together.
   *
   * When using advanced render, each possible item in the list is rendered
   * individually. Then the items are all pasted together.
   */
673
  public function renderItems($items) {
674
    if (!empty($items)) {
675
      $items = $this->prepareItemsByDelta($items);
676
      if ($this->options['multi_type'] == 'separator' || !$this->options['group_rows']) {
677
        $separator = $this->options['multi_type'] == 'separator' ? Xss::filterAdmin($this->options['separator']) : '';
678 679 680 681 682
        $build = [
          '#type' => 'inline_template',
          '#template' => '{{ items | safe_join(separator) }}',
          '#context' => ['separator' => $separator, 'items' => $items],
        ];
683 684
      }
      else {
685
        $build = array(
686 687 688 689 690
          '#theme' => 'item_list',
          '#items' => $items,
          '#title' => NULL,
          '#list_type' => $this->options['multi_type'],
        );
691
      }
692
      return $this->renderer->render($build);
693 694 695
    }
  }

696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799
  /**
   * Adapts the $items according to the delta configuration.
   *
   * This selects displayed deltas, reorders items, and takes offsets into
   * account.
   *
   * @param array $all_values
   *   The items for individual rendering.
   *
   * @return array
   *   The manipulated items.
   */
  protected function prepareItemsByDelta(array $all_values) {
    if ($this->options['delta_reversed']) {
      $all_values = array_reverse($all_values);
    }

    // We are supposed to show only certain deltas.
    if ($this->limit_values) {
      $row = $this->view->result[$this->view->row_index];

      // Offset is calculated differently when row grouping for a field is not
      // enabled. Since there are multiple rows, delta needs to be taken into
      // account, so that different values are shown per row.
      if (!$this->options['group_rows'] && isset($this->aliases['delta']) && isset($row->{$this->aliases['delta']})) {
        $delta_limit = 1;
        $offset = $row->{$this->aliases['delta']};
      }
      // Single fields don't have a delta available so choose 0.
      elseif (!$this->options['group_rows'] && !$this->multiple) {
        $delta_limit = 1;
        $offset = 0;
      }
      else {
        $delta_limit = $this->options['delta_limit'];
        $offset = intval($this->options['delta_offset']);

        // We should only get here in this case if there is an offset, and in
        // that case we are limiting to all values after the offset.
        if ($delta_limit === 0) {
          $delta_limit = count($all_values) - $offset;
        }
      }

      // Determine if only the first and last values should be shown.
      $delta_first_last = $this->options['delta_first_last'];

      $new_values = array();
      for ($i = 0; $i < $delta_limit; $i++) {
        $new_delta = $offset + $i;

        if (isset($all_values[$new_delta])) {
          // If first-last option was selected, only use the first and last
          // values.
          if (!$delta_first_last
            // Use the first value.
            || $new_delta == $offset
            // Use the last value.
            || $new_delta == ($delta_limit + $offset - 1)) {
            $new_values[] = $all_values[$new_delta];
          }
        }
      }
      $all_values = $new_values;
    }

    return $all_values;
  }

  /**
   * {@inheritdoc}
   */
  public function preRender(&$values) {
    parent::preRender($values);
    $this->getEntityFieldRenderer()->preRender($values);
  }

  /**
   * Returns the entity field renderer.
   *
   * @return \Drupal\views\Entity\Render\EntityFieldRenderer
   *   The entity field renderer.
   */
  protected function getEntityFieldRenderer() {
    if (!isset($this->entityFieldRenderer)) {
      // This can be invoked during field handler initialization in which case
      // view fields are not set yet.
      if (!empty($this->view->field)) {
        foreach ($this->view->field as $field) {
          // An entity field renderer can handle only a single relationship.
          if ($field->relationship == $this->relationship && isset($field->entityFieldRenderer)) {
            $this->entityFieldRenderer = $field->entityFieldRenderer;
            break;
          }
        }
      }
      if (!isset($this->entityFieldRenderer)) {
        $entity_type = $this->entityManager->getDefinition($this->getEntityType());
        $this->entityFieldRenderer = new EntityFieldRenderer($this->view, $this->relationship, $this->languageManager, $entity_type, $this->entityManager);
      }
    }
    return $this->entityFieldRenderer;
  }

800
  /**
801 802 803 804 805 806 807
   * Gets an array of items for the field.
   *
   * @param \Drupal\views\ResultRow $values
   *   The result row object containing the values.
   *
   * @return array
   *   An array of items for the field.
808
   */
809
  public function getItems(ResultRow $values) {
810 811
    if (!$this->displayHandler->useGroupBy()) {
      $build_list = $this->getEntityFieldRenderer()->render($values, $this);
812
    }
813 814 815 816 817 818 819 820 821 822
    else {
      // For grouped results we need to retrieve a massaged entity having
      // grouped field values to ensure that "grouped by" values, especially
      // those with multiple cardinality work properly. See
      // \Drupal\views\Tests\QueryGroupByTest::testGroupByFieldWithCardinality.
      $display = [
        'type' => $this->options['type'],
        'settings' => $this->options['settings'],
        'label' => 'hidden',
      ];
823 824 825 826
      // Some bundles might not have a specific field, in which case the faked
      // entity doesn't have it either.
      $entity = $this->createEntityForGroupBy($this->getEntity($values), $values);
      $build_list = isset($entity->{$this->definition['field_name']}) ? $entity->{$this->definition['field_name']}->view($display) : NULL;
827
    }
828

829 830 831
    if (!$build_list) {
      return [];
    }
832 833

    if ($this->options['field_api_classes']) {
834
      return [['rendered' => $this->renderer->render($build_list)]];
835 836
    }

837 838
    // Render using the formatted data itself.
    $items = [];
839 840 841 842
    // Each item is extracted and rendered separately, the top-level formatter
    // render array itself is never rendered, so we extract its bubbleable
    // metadata and add it to each child individually.
    $bubbleable = BubbleableMetadata::createFromRenderArray($build_list);
843
    foreach (Element::children($build_list) as $delta) {
844 845 846 847 848 849 850 851
      BubbleableMetadata::createFromRenderArray($build_list[$delta])
        ->merge($bubbleable)
        ->applyTo($build_list[$delta]);
      $items[$delta] = [
        'rendered' => $build_list[$delta],
        // Add the raw field items (for use in tokens).
        'raw' => $build_list['#items'][$delta],
      ];
852 853 854 855 856
    }
    return $items;
  }

  /**
857
   * Creates a fake entity with grouped field values.
858
   *
859
   * @param \Drupal\Core\Entity\EntityInterface $entity
860
   *   The entity to be processed.
861 862
   * @param \Drupal\views\ResultRow $row
   *   The result row object containing the values.
863
   *
864 865
   * @return bool|\Drupal\Core\Entity\FieldableEntityInterface
   *   Returns a new entity object containing the grouped field values.
866
   */
867 868 869
  protected function createEntityForGroupBy(EntityInterface $entity, ResultRow $row) {
    // Retrieve the correct translation object.
    $processed_entity = clone $this->getEntityFieldRenderer()->getEntityTranslation($entity, $row);
870

871 872 873
    // Copy our group fields into the cloned entity. It is possible this will
    // cause some weirdness, but there is only so much we can hope to do.
    if (!empty($this->group_fields) && isset($entity->{$this->definition['field_name']})) {
874 875 876
      // first, test to see if we have a base value.
      $base_value = array();
      // Note: We would copy original values here, but it can cause problems.
877 878 879
      // For example, text fields store cached filtered values as 'safe_value'
      // which does not appear anywhere in the field definition so we cannot
      // affect it. Other side effects could happen similarly.
880 881
      $data = FALSE;
      foreach ($this->group_fields as $field_name => $column) {
882 883
        if (property_exists($row, $this->aliases[$column])) {
          $base_value[$field_name] = $row->{$this->aliases[$column]};
884 885 886 887 888 889 890 891 892 893
          if (isset($base_value[$field_name])) {
            $data = TRUE;
          }
        }
      }

      // If any of our aggregated fields have data, fake it:
      if ($data) {
        // Now, overwrite the original value with our aggregated value.
        // This overwrites it so there is always just one entry.
894
        $processed_entity->{$this->definition['field_name']} = array($base_value);
895 896
      }
      else {
897
        $processed_entity->{$this->definition['field_name']} = array();
898 899 900
      }
    }

901
    return $processed_entity;
902 903 904 905 906 907
  }

  function render_item($count, $item) {
    return render($item['rendered']);
  }

908
  protected function documentSelfTokens(&$tokens) {
909
    $field = $this->getFieldDefinition();
910
    foreach ($field->getColumns() as $id => $column) {
911
      $tokens['{{ ' . $this->options['id'] . '__' . $id . ' }}'] = $this->t('Raw @column', array('@column' => $id));
912 913 914
    }
  }

915
  protected function addSelfTokens(&$tokens, $item) {
916
    $field = $this->getFieldDefinition();
917
    foreach ($field->getColumns() as $id => $column) {
918 919 920
      // Use \Drupal\Component\Utility\Xss::filterAdmin() because it's user data
      // and we can't be sure it is safe. We know nothing about the data,
      // though, so we can't really do much else.
921
      if (isset($item['raw'])) {
922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943
        $raw = $item['raw'];

        if (is_array($raw)) {
          if (isset($raw[$id]) && is_scalar($raw[$id])) {
            $tokens['{{ ' . $this->options['id'] . '__' . $id . ' }}'] = Xss::filterAdmin($raw[$id]);
          }
          else {
            // Make sure that empty values are replaced as well.
            $tokens['{{ ' . $this->options['id'] . '__' . $id . ' }}'] = '';
          }
        }

        if (is_object($raw)) {
          $property = $raw->get($id);
          if (!empty($property)) {
            $tokens['{{ ' . $this->options['id'] . '__' . $id . ' }}'] = Xss::filterAdmin($property->getValue());
          }
          else {
            // Make sure that empty values are replaced as well.
            $tokens['{{ ' . $this->options['id'] . '__' . $id . ' }}'] = '';
          }
        }
944 945 946 947
      }
    }
  }

948 949 950
  /**
   * {@inheritdoc}
   */
951
  public function calculateDependencies() {
952 953
    $dependencies = parent::calculateDependencies();

954
    // Add the module providing the configured field storage as a dependency.
955 956 957
    if (($field_storage_definition = $this->getFieldStorageDefinition()) && $field_storage_definition instanceof EntityInterface) {
      $dependencies['config'][] = $field_storage_definition->getConfigDependencyName();
    }
958
    // Add the module providing the formatter.
959
    if (!empty($this->options['type'])) {
960 961 962 963
      $dependencies['module'][] = $this->formatterPluginManager->getDefinition($this->options['type'])['provider'];
    }

    return $dependencies;
964 965
  }

966 967 968
  /**
   * {@inheritdoc}
   */
969 970
  public function getCacheMaxAge() {
    return Cache::PERMANENT;
971 972 973 974 975 976
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheContexts() {
977
    return $this->getEntityFieldRenderer()->getCacheContexts();
978
  }
979

980 981 982 983 984 985 986 987 988 989 990 991
  /**
   * {@inheritdoc}
   */
  public function getCacheTags() {
    $field_definition = $this->getFieldDefinition();
    $field_storage_definition = $this->getFieldStorageDefinition();
    return Cache::mergeTags(
      $field_definition instanceof CacheableDependencyInterface ? $field_definition->getCacheTags() : [],
      $field_storage_definition instanceof CacheableDependencyInterface ? $field_storage_definition->getCacheTags() : []
    );
  }

992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005
  /**
   * Gets the table mapping for the entity type of the field.
   *
   * @return \Drupal\Core\Entity\Sql\DefaultTableMapping
   *   The table mapping.
   */
  protected function getTableMapping() {
    return $this->entityManager->getStorage($this->definition['entity_type'])->getTableMapping();
  }

  /**
   * {@inheritdoc}
   */
  public function getValue(ResultRow $values, $field = NULL) {
1006 1007 1008
    $entity = $this->getEntity($values);
    // Some bundles might not have a specific field, in which case the entity
    // (potentially a fake one) doesn't have it either.
1009
    /** @var \Drupal\Core\Field\FieldItemListInterface $field_item_list */
1010 1011 1012 1013 1014 1015 1016
    $field_item_list = isset($entity->{$this->definition['field_name']}) ? $entity->{$this->definition['field_name']} : NULL;

    if (!isset($field_item_list)) {
      // There isn't anything we can do without a valid field.
      return NULL;
    }

1017 1018 1019 1020
    $field_item_definition = $field_item_list->getFieldDefinition();

    if ($field_item_definition->getFieldStorageDefinition()->getCardinality() == 1) {
      return $field ? $field_item_list->$field : $field_item_list->value;
1021 1022
    }

1023 1024 1025 1026 1027
    $values = [];
    foreach ($field_item_list as $field_item) {
      $values[] = $field ? $field_item->$field : $field_item->value;
    }
    return $values;
1028 1029
  }

1030
}