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

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

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

10
use Drupal\Component\Utility\SafeMarkup;
11
use Drupal\Component\Utility\Xss;
12
use Drupal\Core\Entity\EntityInterface;
13
use Drupal\Core\Entity\EntityManagerInterface;
14
use Drupal\Core\Entity\EntityStorageInterface;
15
use Drupal\Core\Field\BaseFieldDefinition;
16
use Drupal\Core\Field\FieldStorageDefinitionInterface;
17
use Drupal\Core\Field\FormatterPluginManager;
18
use Drupal\Core\Form\FormStateInterface;
19
use Drupal\Core\Language\LanguageInterface;
20
use Drupal\Core\Language\LanguageManagerInterface;
21
use Drupal\Core\Render\Element;
22
use Drupal\Core\Session\AccountInterface;
23
use Drupal\views\Plugin\views\display\DisplayPluginBase;
24
use Drupal\views\Plugin\views\field\FieldPluginBase;
25 26
use Drupal\views\ViewExecutable;
use Drupal\views\Views;
27
use Symfony\Component\DependencyInjection\ContainerInterface;
28 29 30 31 32

/**
 * A field that displays fieldapi fields.
 *
 * @ingroup views_field_handlers
33
 *
34
 * @ViewsField("field")
35 36
 */
class Field extends FieldPluginBase {
37

38
  /**
39
   * An array to store field renderable arrays for use by renderItems().
40
   *
41 42 43 44 45
   * @var array
   */
  public $items = array();

  /**
46
   * The field definition to use.
47
   *
48 49
   * A field storage definition turned into a field definition, so it can be
   * used with widgets and formatters. See
50
   * BaseFieldDefinition::createFromFieldStorageDefinition().
51 52
   *
   * @var \Drupal\Core\Field\FieldDefinitionInterface
53
   */
54 55 56 57
  protected $fieldDefinition;

  /**
   * The field config.
58 59
   *
   * @var \Drupal\field\FieldStorageConfigInterface
60
   */
61
  protected $fieldStorageConfig;
62 63 64

  /**
   * Does the field supports multiple field values.
65
   *
66 67 68 69 70 71
   * @var bool
   */
  public $multiple;

  /**
   * Does the rendered fields get limited.
72
   *
73 74 75 76 77 78
   * @var bool
   */
  public $limit_values;

  /**
   * A shortcut for $view->base_table.
79
   *
80 81 82 83
   * @var string
   */
  public $base_table;

84 85 86 87 88 89 90
  /**
   * An array of formatter options.
   *
   * @var array
   */
  protected $formatterOptions;

91 92 93
  /**
   * The entity manager.
   *
94
   * @var \Drupal\Core\Entity\EntityManagerInterface
95 96 97
   */
  protected $entityManager;

98 99 100
  /**
   * The field formatter plugin manager.
   *
101
   * @var \Drupal\Core\Field\FormatterPluginManager
102 103 104
   */
  protected $formatterPluginManager;

105 106 107
  /**
   * The language manager.
   *
108
   * @var \Drupal\Core\Language\LanguageManagerInterface
109 110 111
   */
  protected $languageManager;

112 113 114 115 116 117 118
  /**
   * 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.
119
   * @param mixed $plugin_definition
120
   *   The plugin implementation definition.
121
   * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
122
   *   The field formatter plugin manager.
123
   * @param \Drupal\Core\Field\FormatterPluginManager $formatter_plugin_manager
124
   *   The field formatter plugin manager.
125
   * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
126
   *   The language manager.
127
   */
128
  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityManagerInterface $entity_manager, FormatterPluginManager $formatter_plugin_manager, LanguageManagerInterface $language_manager) {
129 130
    parent::__construct($configuration, $plugin_id, $plugin_definition);

131
    $this->entityManager = $entity_manager;
132
    $this->formatterPluginManager = $formatter_plugin_manager;
133
    $this->languageManager = $language_manager;
134 135 136 137 138
  }

  /**
   * {@inheritdoc}
   */
139
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
140 141 142 143
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
144
      $container->get('entity.manager'),
145 146
      $container->get('plugin.manager.field.formatter'),
      $container->get('language_manager')
147 148 149
    );
  }

150 151 152 153 154 155 156 157
  /**
   * Gets the field definition.
   *
   * @return \Drupal\Core\Field\FieldDefinitionInterface
   *   The field definition used by this handler.
   */
  protected function getFieldDefinition() {
    if (!$this->fieldDefinition) {
158
      $field_storage_config = $this->getFieldStorageConfig();
159
      $this->fieldDefinition = BaseFieldDefinition::createFromFieldStorageDefinition($field_storage_config);
160 161 162 163 164 165 166
    }
    return $this->fieldDefinition;
  }

  /**
   * Gets the field configuration.
   *
167
   * @return \Drupal\field\FieldStorageConfigInterface
168
   */
169 170
  protected function getFieldStorageConfig() {
    if (!$this->fieldStorageConfig) {
171
      $field_storage_definitions = \Drupal::entityManager()->getFieldStorageDefinitions($this->definition['entity_type']);
172
      $this->fieldStorageConfig = $field_storage_definitions[$this->definition['field_name']];
173
    }
174
    return $this->fieldStorageConfig;
175 176
  }

177 178 179 180 181
  /**
   * Overrides \Drupal\views\Plugin\views\field\FieldPluginBase::init().
   */
  public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
    parent::init($view, $display, $options);
182 183 184 185

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

186
    $field_definition = $this->getFieldDefinition();
187 188
    $cardinality = $field_definition->getFieldStorageDefinition()->getCardinality();
    if ($field_definition->getFieldStorageDefinition()->isMultiple()) {
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
      $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.
204
      if ((intval($this->options['delta_limit']) && ($this->options['delta_limit'] != $cardinality)) || intval($this->options['delta_offset'])) {
205 206 207 208 209 210
        $this->limit_values = TRUE;
      }
    }
  }

  /**
211
   * {@inheritdoc}
212
   */
213
  public function access(AccountInterface $account) {
214
    $base_table = $this->get_base_table();
215 216
    $access_control_handler = $this->entityManager->getAccessControlHandler($this->definition['entity_tables'][$base_table]);
    return $access_control_handler->fieldAccess('view', $this->getFieldDefinition(), $account);
217 218 219 220 221 222 223 224 225 226 227
  }

  /**
   * Set the base_table and base_table_alias.
   *
   * @return string
   *   The base table which is used in the current view "context".
   */
  function get_base_table() {
    if (!isset($this->base_table)) {
      // This base_table is coming from the entity not the field.
228
      $this->base_table = $this->view->storage->get('base_table');
229 230 231 232 233

      // If the current field is under a relationship you can't be sure that the
      // base table of the view is the base table of the current field.
      // For example a field from a node author on a node view does have users as base table.
      if (!empty($this->options['relationship']) && $this->options['relationship'] != 'none') {
234
        $relationships = $this->view->display_handler->getOption('relationships');
235 236
        if (!empty($relationships[$this->options['relationship']])) {
          $options = $relationships[$this->options['relationship']];
237
          $data = Views::viewsData()->get($options['table']);
238 239 240 241 242 243 244 245 246 247 248
          $this->base_table = $data[$options['field']]['relationship']['base'];
        }
      }
    }

    return $this->base_table;
  }

  /**
   * Called to add the field to a query.
   *
249 250
   * By default, all needed data is taken from entities loaded by the query
   * plugin. Columns are added only if they are used in groupings.
251
   */
252
  public function query($use_groupby = FALSE) {
253 254 255 256
    $this->get_base_table();

    $entity_type = $this->definition['entity_tables'][$this->base_table];
    $fields = $this->additional_fields;
257
    // No need to add the entity type.
258 259 260 261 262
    $entity_type_key = array_search('entity_type', $fields);
    if ($entity_type_key !== FALSE) {
      unset($fields[$entity_type_key]);
    }

263
    $field_definition = $this->getFieldDefinition();
264 265 266 267 268 269 270 271 272
    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();

      $fields = array();
273
      $rkey = $this->definition['is revision'] ? EntityStorageInterface::FIELD_LOAD_REVISION : EntityStorageInterface::FIELD_LOAD_CURRENT;
274 275 276
      // Go through the list and determine the actual column name from field api.
      foreach ($options as $column) {
        $name = $column;
277 278
        if (isset($field_definition['storage_details']['sql'][$rkey][$this->table][$column])) {
          $name = $field_definition['storage_details']['sql'][$rkey][$this->table][$column];
279 280 281 282 283 284 285 286 287 288
        }

        $fields[$column] = $name;
      }

      $this->group_fields = $fields;
    }

    // Add additional fields (and the table join itself) if needed.
    if ($this->add_field_table($use_groupby)) {
289
      $this->ensureMyTable();
290
      $this->addAdditionalFields($fields);
291

292 293 294 295
      // If we are grouping by something on this field, we want to group by
      // the displayed value, which is translated. So, we need to figure out
      // which language should be used to translate the value. See also
      // $this->field_langcode().
296
      $field = $field_definition;
297
      if ($field->isTranslatable() && !empty($this->view->display_handler->options['field_langcode_add_to_query'])) {
298
        $column = $this->tableAlias . '.langcode';
299 300 301 302 303
        $langcode = $this->view->display_handler->options['field_langcode'];
        $substitutions = static::queryLanguageSubstitutions();
        if (isset($substitutions[$langcode])) {
          $langcode = $substitutions[$langcode];
        }
304
        $placeholder = $this->placeholder();
305
        $langcode_fallback_candidates = $this->languageManager->getFallbackCandidates(array('langcode' => $langcode, 'operation' => 'views_query', 'data' => $this));
306
        $this->query->addWhereExpression(0, "$column IN($placeholder) OR $column IS NULL", array($placeholder => $langcode_fallback_candidates));
307 308 309 310 311 312 313 314
      }
    }
  }

  /**
   * Determine if the field table should be added to the query.
   */
  function add_field_table($use_groupby) {
315 316
    // Grouping is enabled.
    if ($use_groupby) {
317 318 319 320 321 322 323 324 325 326 327 328
      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;
  }

  /**
   * Determine if this field is click sortable.
   */
329
  public function clickSortable() {
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
    // Not click sortable in any case.
    if (empty($this->definition['click sortable'])) {
      return FALSE;
    }
    // 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;
    }
    return TRUE;
  }

  /**
   * Called to determine what to tell the clicksorter.
   */
346
  public function clickSort($order) {
347 348 349 350 351
    // No column selected, can't continue.
    if (empty($this->options['click_sort_column'])) {
      return;
    }

352
    $this->ensureMyTable();
353 354
    $entity_type_id = $this->definition['entity_type'];
    $field_storage_definitions = $this->entityManager->getFieldStorageDefinitions($entity_type_id);
355
    $field_storage = $field_storage_definitions[$this->definition['field_name']];
356 357 358
    /** @var \Drupal\Core\Entity\Sql\DefaultTableMapping $table_mapping */
    $table_mapping = $this->entityManager->getStorage($entity_type_id)->getTableMapping();
    $column = $table_mapping->getFieldColumnName($field_storage, $this->options['click_sort_column']);
359 360
    if (!isset($this->aliases[$column])) {
      // Column is not in query; add a sort on it (without adding the column).
361
      $this->aliases[$column] = $this->tableAlias . '.' . $column;
362
    }
363
    $this->query->addOrderBy(NULL, NULL, $order, $this->aliases[$column]);
364 365
  }

366 367
  protected function defineOptions() {
    $options = parent::defineOptions();
368

369
    $field_storage_definitions = $this->entityManager->getFieldStorageDefinitions($this->definition['entity_type']);
370 371 372
    $field_storage = $field_storage_definitions[$this->definition['field_name']];
    $field_type = \Drupal::service('plugin.manager.field.field_type')->getDefinition($field_storage->getType());
    $column_names = array_keys($field_storage->getColumns());
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
    $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,
    );
    $options['type'] = array(
      'default' => $field_type['default_formatter'],
    );
    $options['settings'] = array(
      'default' => array(),
    );
    $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,
      'bool' => TRUE,
    );
    // If we know the exact number of allowed values, then that can be
    // the default. Otherwise, default to 'all'.
    $options['delta_limit'] = array(
407
      'default' => ($field_storage->getCardinality() > 1) ? $field_storage->getCardinality() : 'all',
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
    );
    $options['delta_offset'] = array(
      'default' => 0,
    );
    $options['delta_reversed'] = array(
      'default' => FALSE,
      'bool' => TRUE,
    );
    $options['delta_first_last'] = array(
      'default' => FALSE,
      'bool' => TRUE,
    );

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

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

    return $options;
  }

436 437 438
  /**
   * {@inheritdoc}
   */
439
  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
440
    parent::buildOptionsForm($form, $form_state);
441

442
    $field = $this->getFieldDefinition();
443
    $formatters = $this->formatterPluginManager->getOptions($field->getType());
444
    $column_names = array_keys($field->getColumns());
445 446 447 448 449 450 451

    // 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.
452
    if (count($field->getColumns()) == 1) {
453 454 455 456 457 458 459 460 461
      $form['click_sort_column'] = array(
        '#type' => 'value',
        '#value' => isset($column_names[0]) ? $column_names[0] : '',
      );
    }
    else {
      $form['click_sort_column'] = array(
        '#type' => 'select',
        '#title' => t('Column used for click sorting'),
462
        '#options' => array_combine($column_names, $column_names),
463 464 465 466 467 468 469 470 471 472 473
        '#default_value' => $this->options['click_sort_column'],
        '#description' => t('Used by Style: Table to determine the actual column to click sort the field on. The default is usually fine.'),
      );
    }

    $form['type'] = array(
      '#type' => 'select',
      '#title' => t('Formatter'),
      '#options' => $formatters,
      '#default_value' => $this->options['type'],
      '#ajax' => array(
474
        'path' => views_ui_build_form_path($form_state),
475
      ),
476
      '#submit' => array(array($this, 'submitTemporaryForm')),
477 478 479 480 481 482 483
      '#executes_submit_callback' => TRUE,
    );

    $form['field_api_classes'] = array(
      '#title' => t('Use field template'),
      '#type' => 'checkbox',
      '#default_value' => $this->options['field_api_classes'],
484
      '#description' => 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.'),
485 486 487 488 489 490 491 492 493 494 495
      '#fieldset' => 'style_settings',
      '#weight' => 20,
    );

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

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

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

498
    $options = array(
499
      'field_definition' => $field,
500 501 502 503 504 505 506 507 508
      'configuration' => array(
        'type' => $format,
        'settings' => $settings,
        'label' => '',
        'weight' => 0,
      ),
      'view_mode' => '_custom',
    );

509 510
    // Get the settings form.
    $settings_form = array('#value' => array());
511
    if ($formatter = $this->formatterPluginManager->getInstance($options)) {
512
      $settings_form = $formatter->settingsForm($form, $form_state);
513 514 515 516 517 518 519
    }
    $form['settings'] = $settings_form;
  }

  /**
   * Provide options for multiple value fields.
   */
520
  function multiple_options_form(&$form, FormStateInterface $form_state) {
521
    $field = $this->getFieldDefinition();
522 523

    $form['multiple_field_settings'] = array(
524
      '#type' => 'details',
525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540
      '#title' => t('Multiple field settings'),
      '#weight' => 5,
    );

    $form['group_rows'] = array(
      '#title' => t('Display all values in the same row'),
      '#type' => 'checkbox',
      '#default_value' => $this->options['group_rows'],
      '#description' => 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.'),
      '#fieldset' => 'multiple_field_settings',
    );

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

541
    if ($field->getCardinality() == FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED) {
542 543 544 545 546 547
      $type = 'textfield';
      $options = NULL;
      $size = 5;
    }
    else {
      $type = 'select';
548 549
      $range = range(1, $field->getCardinality());
      $options = array_combine($range, $range);
550 551 552 553 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 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 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 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642
      $size = 1;
    }
    $form['multi_type'] = array(
      '#type' => 'radios',
      '#title' => t('Display type'),
      '#options' => array(
        'ul' => t('Unordered list'),
        'ol' => t('Ordered list'),
        'separator' => t('Simple separator'),
      ),
      '#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',
      '#title' => t('Separator'),
      '#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',
    );

    list($prefix, $suffix) = explode('@count', t('starting from @count'));
    $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),
        ),
      ),
      '#description' => t('(first item is 0)'),
      '#fieldset' => 'multiple_field_settings',
    );
    $form['delta_reversed'] = array(
      '#title' => t('Reversed'),
      '#type' => 'checkbox',
      '#default_value' => $this->options['delta_reversed'],
      '#suffix' => $suffix,
      '#states' => array(
        'visible' => array(
          ':input[name="options[group_rows]"]' => array('checked' => TRUE),
        ),
      ),
      '#description' => t('(start from last values)'),
      '#fieldset' => 'multiple_field_settings',
    );
    $form['delta_first_last'] = array(
      '#title' => t('First and last only'),
      '#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.
   */
643
  public function buildGroupByForm(&$form, FormStateInterface $form_state) {
644
    parent::buildGroupByForm($form, $form_state);
645 646
    // With "field API" fields, the column target of the grouping function
    // and any additional grouping columns must be specified.
647

648
    $field_columns = array_keys($this->getFieldDefinition()->getColumns());
649 650
    $group_columns = array(
      'entity_id' => t('Entity ID'),
651
    ) + array_map('ucfirst', array_combine($field_columns, $field_columns));
652 653 654 655 656 657 658 659 660

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

661 662 663 664 665
    $options = array(
      'bundle' => 'Bundle',
      'language' => 'Language',
      'entity_type' => 'Entity_type',
    );
666 667 668 669 670 671 672 673 674 675
    // Add on defined fields, noting that they're prefixed with the field name.
    $form['group_columns'] = array(
      '#type' => 'checkboxes',
      '#title' => t('Group columns (additional)'),
      '#default_value' => $this->options['group_columns'],
      '#description' => t('Select any additional columns of this field to include in the query and to group on.'),
      '#options' => $options + $group_columns,
    );
  }

676
  public function submitGroupByForm(&$form, FormStateInterface $form_state) {
677
    parent::submitGroupByForm($form, $form_state);
678
    $item = &$form_state['handler']->options;
679 680

    // Add settings for "field API" fields.
681 682
    $item['group_column'] = $form_state->getValue(array('options', 'group_column'));
    $item['group_columns'] = array_filter($form_state->getValue(array('options', 'group_columns')));
683 684 685 686 687 688 689 690
  }

  /**
   * 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.
   */
691
  protected function renderItems($items) {
692
    if (!empty($items)) {
693
      $output = '';
694
      if (!$this->options['group_rows']) {
695 696 697 698
        foreach ($items as $item) {
          $output .= SafeMarkup::escape($item);
        }
        return SafeMarkup::set($output);
699 700
      }
      if ($this->options['multi_type'] == 'separator') {
701 702 703 704 705 706 707 708
        $output = '';
        $separator = '';
        $escaped_separator = Xss::filterAdmin($this->options['separator']);
        foreach ($items as $item) {
          $output .= $separator . SafeMarkup::escape($item);
          $separator = $escaped_separator;
        }
        return SafeMarkup::set($output);
709 710
      }
      else {
711 712 713 714 715 716 717
        $item_list = array(
          '#theme' => 'item_list',
          '#items' => $items,
          '#title' => NULL,
          '#list_type' => $this->options['multi_type'],
        );
        return drupal_render($item_list);
718 719 720 721
      }
    }
  }

722 723 724
  /**
   * Return an array of items for the field.
   */
725
  public function getItems($values) {
726
    $original_entity = $this->getEntity($values);
727 728 729 730 731 732 733
    if (!$original_entity) {
      return array();
    }
    $entity = $this->process_entity($original_entity);
    if (!$entity) {
      return array();
    }
734

735 736 737 738 739 740 741 742 743
    $display = array(
      'type' => $this->options['type'],
      'settings' => $this->options['settings'],
      'label' => 'hidden',
      // Pass the View object in the display so that fields can act on it.
      'views_view' => $this->view,
      'views_field' => $this,
      'views_row_id' => $this->view->row_index,
    );
744
    $render_array = $entity->get($this->definition['field_name'])->view($display);
745 746 747 748 749 750

    $items = array();
    if ($this->options['field_api_classes']) {
      return array(array('rendered' => drupal_render($render_array)));
    }

751
    foreach (Element::children($render_array) as $count) {
752
      $items[$count]['rendered'] = $render_array[$count];
753 754 755 756
      // FieldItemListInterface::view() adds an #access property to the render
      // array that determines whether or not the current user is allowed to
      // view the field in the context of the current entity. We need to respect
      // this parameter when we pull out the children of the field array for
757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775
      // rendering.
      if (isset($render_array['#access'])) {
        $items[$count]['rendered']['#access'] = $render_array['#access'];
      }
      // Only add the raw field items (for use in tokens) if the current user
      // has access to view the field content.
      if ((!isset($items[$count]['rendered']['#access']) || $items[$count]['rendered']['#access']) && !empty($render_array['#items'][$count])) {
        $items[$count]['raw'] = $render_array['#items'][$count];
      }
    }
    return $items;
  }

  /**
   * Process an entity before using it for rendering.
   *
   * Replaces values with aggregated values if aggregation is enabled.
   * Takes delta settings into account (@todo remove in #1758616).
   *
776
   * @param \Drupal\Core\Entity\EntityInterface $entity
777 778 779 780 781
   *   The entity to be processed.
   *
   * @return
   *   TRUE if the processing completed successfully, otherwise FALSE.
   */
782
  function process_entity(EntityInterface $entity) {
783
    $processed_entity = clone $entity;
784

785
    $langcode = $this->field_langcode($processed_entity);
786 787
    $processed_entity = $processed_entity->getTranslation($langcode);

788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811
    // If we are grouping, copy our group fields into the cloned entity.
    // It's possible this will cause some weirdness, but there's only
    // so much we can hope to do.
    if (!empty($this->group_fields)) {
      // 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.
      // For example, text fields store cached filtered values as
      // 'safe_value' which doesn't appear anywhere in the field definition
      // so we can't affect it. Other side effects could happen similarly.
      $data = FALSE;
      foreach ($this->group_fields as $field_name => $column) {
        if (property_exists($values, $this->aliases[$column])) {
          $base_value[$field_name] = $values->{$this->aliases[$column]};
          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.
812
        $processed_entity->{$this->definition['field_name']} = array($base_value);
813 814
      }
      else {
815
        $processed_entity->{$this->definition['field_name']} = array();
816 817 818 819
      }
    }

    // The field we are trying to display doesn't exist on this entity.
820 821
    if (!isset($processed_entity->{$this->definition['field_name']})) {
      return FALSE;
822 823 824
    }

    // We are supposed to show only certain deltas.
825
    if ($this->limit_values && !empty($processed_entity->{$this->definition['field_name']})) {
826
      $all_values = !empty($processed_entity->{$this->definition['field_name']}) ? $processed_entity->{$this->definition['field_name']}->getValue() : array();
827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871
      if ($this->options['delta_reversed']) {
        $all_values = array_reverse($all_values);
      }

      // Offset is calculated differently when row grouping for a field is
      // not enabled. Since there are multiple rows, the 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($values->{$this->aliases['delta']})) {
        $delta_limit = 1;
        $offset = $values->{$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's an offset, and
        // in that case we're limiting to all values after the offset.
        if ($delta_limit == 'all') {
          $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];
          }
        }
      }
872
      $processed_entity->{$this->definition['field_name']} = $new_values;
873 874
    }

875
    return $processed_entity;
876 877 878 879 880 881
  }

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

882
  protected function documentSelfTokens(&$tokens) {
883
    $field = $this->getFieldDefinition();
884
    foreach ($field->getColumns() as $id => $column) {
885 886 887 888
      $tokens['[' . $this->options['id'] . '-' . $id . ']'] = t('Raw @column', array('@column' => $id));
    }
  }

889
  protected function addSelfTokens(&$tokens, $item) {
890
    $field = $this->getFieldDefinition();
891
    foreach ($field->getColumns() as $id => $column) {
892 893 894
      // 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.
895 896 897 898 899 900 901 902

      if (isset($item['raw'])) {
        // If $item['raw'] is an array then we can use as is, if it's an object
        // we cast it to an array, if it's neither, we can't use it.
        $raw = is_array($item['raw']) ? $item['raw'] :
               (is_object($item['raw']) ? (array)$item['raw'] : NULL);
      }
      if (isset($raw) && isset($raw[$id]) && is_scalar($raw[$id])) {
903
        $tokens['[' . $this->options['id'] . '-' . $id . ']'] = Xss::filterAdmin($raw[$id]);
904 905
      }
      else {
906
        // Make sure that empty values are replaced as well.
907 908 909 910 911 912 913 914 915
        $tokens['[' . $this->options['id'] . '-' . $id . ']'] = '';
      }
    }
  }

  /**
   * Return the language code of the language the field should be displayed in,
   * according to the settings.
   */
916
  function field_langcode(EntityInterface $entity) {
917
    if ($this->getFieldDefinition()->isTranslatable()) {
918 919 920 921 922
      $langcode = $this->view->display_handler->options['field_langcode'];
      $substitutions = static::queryLanguageSubstitutions();
      if (isset($substitutions[$langcode])) {
        $langcode = $substitutions[$langcode];
      }
923

924
      // Give the Entity Field API a chance to fallback to a different language
925 926 927 928
      // (or LanguageInterface::LANGCODE_NOT_SPECIFIED), in case the field has
      // no data for the selected language. FieldItemListInterface::view() does
      // this as well, but since the returned language code is used before
      // calling it, the fallback needs to happen explicitly.
929
      $langcode = $this->entityManager->getTranslationFromContext($entity, $langcode)->language()->id;
930

931
      return $langcode;
932 933
    }
    else {
934
      return LanguageInterface::LANGCODE_NOT_SPECIFIED;
935 936
    }
  }
937

938 939 940 941
  /**
   * {@inheritdoc}
   */
  public function getDependencies() {
942 943
    // Add the module providing the configured field storage as a dependency.
    return array('entity' => array($this->getFieldStorageConfig()->getConfigDependencyName()));
944 945 946
  }


947
}