EntityDisplayFormBase.php 32.9 KB
Newer Older
1
2
<?php

3
namespace Drupal\field_ui\Form;
4

5
use Drupal\Component\Plugin\Factory\DefaultFactory;
6
use Drupal\Component\Plugin\PluginManagerBase;
7
8
9
use Drupal\Core\Entity\EntityForm;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityWithPluginCollectionInterface;
10
use Drupal\Core\Field\FieldDefinitionInterface;
11
use Drupal\Core\Field\FieldTypePluginManagerInterface;
12
use Drupal\Core\Field\PluginSettingsInterface;
13
use Drupal\Core\Form\FormStateInterface;
14
use Drupal\Core\Routing\RouteMatchInterface;
15
use Drupal\field_ui\Element\FieldUiTable;
16
use Drupal\field_ui\FieldUI;
17
18

/**
19
 * Base class for EntityDisplay edit forms.
20
 */
21
abstract class EntityDisplayFormBase extends EntityForm {
22

23
24
25
26
27
28
29
  /**
   * The display context. Either 'view' or 'form'.
   *
   * @var string
   */
  protected $displayContext;

30
31
32
33
34
35
36
37
38
39
40
41
42
43
  /**
   * The widget or formatter plugin manager.
   *
   * @var \Drupal\Component\Plugin\PluginManagerBase
   */
  protected $pluginManager;

  /**
   * A list of field types.
   *
   * @var array
   */
  protected $fieldTypes;

44
  /**
45
   * The entity being used by this form.
46
   *
47
   * @var \Drupal\Core\Entity\Display\EntityDisplayInterface
48
   */
49
  protected $entity;
50

51
  /**
52
   * Constructs a new EntityDisplayFormBase.
53
   *
54
   * @param \Drupal\Core\Field\FieldTypePluginManagerInterface $field_type_manager
55
   *   The field type manager.
56
57
58
   * @param \Drupal\Component\Plugin\PluginManagerBase $plugin_manager
   *   The widget or formatter plugin manager.
   */
59
  public function __construct(FieldTypePluginManagerInterface $field_type_manager, PluginManagerBase $plugin_manager) {
60
    $this->fieldTypes = $field_type_manager->getDefinitions();
61
    $this->pluginManager = $plugin_manager;
62
63
64
65
66
  }

  /**
   * {@inheritdoc}
   */
67
68
69
  public function getEntityFromRouteMatch(RouteMatchInterface $route_match, $entity_type_id) {
    $route_parameters = $route_match->getParameters()->all();

70
    return $this->getEntityDisplay($route_parameters['entity_type_id'], $route_parameters['bundle'], $route_parameters[$this->displayContext . '_mode_name']);
71
72
73
  }

  /**
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
   * Get the regions needed to create the overview form.
   *
   * @return array
   *   Example usage:
   *   @code
   *     return array(
   *       'content' => array(
   *         // label for the region.
   *         'title' => $this->t('Content'),
   *         // Indicates if the region is visible in the UI.
   *         'invisible' => TRUE,
   *         // A message to indicate that there is nothing to be displayed in
   *         // the region.
   *         'message' => $this->t('No field is displayed.'),
   *       ),
   *     );
   *   @endcode
91
92
93
94
   */
  public function getRegions() {
    return array(
      'content' => array(
95
        'title' => $this->t('Content'),
96
        'invisible' => TRUE,
97
        'message' => $this->t('No field is displayed.')
98
99
      ),
      'hidden' => array(
100
        'title' => $this->t('Disabled', array(), array('context' => 'Plural')),
101
        'message' => $this->t('No field is hidden.')
102
103
104
105
      ),
    );
  }

106
107
108
109
110
111
112
113
114
115
116
117
118
119
  /**
   * Returns an associative array of all regions.
   *
   * @return array
   *   An array containing the region options.
   */
  public function getRegionOptions() {
    $options = array();
    foreach ($this->getRegions() as $region => $data) {
      $options[$region] = $data['title'];
    }
    return $options;
  }

120
121
122
123
124
125
126
127
  /**
   * Collects the definitions of fields whose display is configurable.
   *
   * @return \Drupal\Core\Field\FieldDefinitionInterface[]
   *   The array of field definitions
   */
  protected function getFieldDefinitions() {
    $context = $this->displayContext;
128
    return array_filter($this->entityManager->getFieldDefinitions($this->entity->getTargetEntityTypeId(), $this->entity->getTargetBundle()), function(FieldDefinitionInterface $field_definition) use ($context) {
129
130
131
132
      return $field_definition->isDisplayConfigurable($context);
    });
  }

133
134
135
  /**
   * {@inheritdoc}
   */
136
137
  public function form(array $form, FormStateInterface $form_state) {
    $form = parent::form($form, $form_state);
138

139
    $field_definitions = $this->getFieldDefinitions();
140
141
142
    $extra_fields = $this->getExtraFields();

    $form += array(
143
144
      '#entity_type' => $this->entity->getTargetEntityTypeId(),
      '#bundle' => $this->entity->getTargetBundle(),
145
      '#fields' => array_keys($field_definitions),
146
147
148
      '#extra' => array_keys($extra_fields),
    );

149
    if (empty($field_definitions) && empty($extra_fields) && $route_info = FieldUI::getOverviewRouteInfo($this->entity->getTargetEntityTypeId(), $this->entity->getTargetBundle())) {
150
      drupal_set_message($this->t('There are no fields yet added. You can add new fields on the <a href=":link">Manage fields</a> page.', array(':link' => $route_info->toString())), 'warning');
151
152
153
154
155
156
157
158
159
160
161
      return $form;
    }

    $table = array(
      '#type' => 'field_ui_table',
      '#header' => $this->getTableHeader(),
      '#regions' => $this->getRegions(),
      '#attributes' => array(
        'class' => array('field-ui-overview'),
        'id' => 'field-display-overview',
      ),
162
163
164
165
166
167
168
169
170
171
172
173
174
175
      '#tabledrag' => array(
        array(
          'action' => 'order',
          'relationship' => 'sibling',
          'group' => 'field-weight',
        ),
        array(
          'action' => 'match',
          'relationship' => 'parent',
          'group' => 'field-parent',
          'subgroup' => 'field-parent',
          'source' => 'field-name',
        ),
      ),
176
177
178
    );

    // Field rows.
179
    foreach ($field_definitions as $field_name => $field_definition) {
180
      $table[$field_name] = $this->buildFieldRow($field_definition, $form, $form_state);
181
182
183
184
    }

    // Non-field elements.
    foreach ($extra_fields as $field_id => $extra_field) {
185
      $table[$field_id] = $this->buildExtraFieldRow($field_id, $extra_field);
186
187
188
189
190
    }

    $form['fields'] = $table;

    // Custom display settings.
191
    if ($this->entity->getMode() == 'default') {
192
      // Only show the settings if there is at least one custom display mode.
193
194
195
196
      $display_mode_options = $this->getDisplayModeOptions();
      // Unset default option.
      unset($display_mode_options['default']);
      if ($display_mode_options) {
197
198
        $form['modes'] = array(
          '#type' => 'details',
199
          '#title' => $this->t('Custom display settings'),
200
        );
201
        // Prepare default values for the 'Custom display settings' checkboxes.
202
        $default = array();
203
204
        if ($enabled_displays = array_filter($this->getDisplayStatuses())) {
          $default = array_keys(array_intersect_key($display_mode_options, $enabled_displays));
205
206
207
        }
        $form['modes']['display_modes_custom'] = array(
          '#type' => 'checkboxes',
208
          '#title' => $this->t('Use custom display settings for the following @display_context modes', ['@display_context' => $this->displayContext]),
209
          '#options' => $display_mode_options,
210
211
          '#default_value' => $default,
        );
212
213
        // Provide link to manage display modes.
        $form['modes']['display_modes_link'] = $this->getDisplayModesLink();
214
215
216
217
218
219
220
221
222
223
224
225
      }
    }

    // In overviews involving nested rows from contributed modules (i.e
    // field_group), the 'plugin type' selects can trigger a series of changes
    // in child rows. The #ajax behavior is therefore not attached directly to
    // the selects, but triggered by the client-side script through a hidden
    // #ajax 'Refresh' button. A hidden 'refresh_rows' input tracks the name of
    // affected rows.
    $form['refresh_rows'] = array('#type' => 'hidden');
    $form['refresh'] = array(
      '#type' => 'submit',
226
      '#value' => $this->t('Refresh'),
227
      '#op' => 'refresh_table',
228
      '#submit' => array('::multistepSubmit'),
229
      '#ajax' => array(
230
        'callback' => '::multistepAjax',
231
232
233
234
235
236
237
238
239
240
        'wrapper' => 'field-display-overview-wrapper',
        'effect' => 'fade',
        // The button stays hidden, so we hide the Ajax spinner too. Ad-hoc
        // spinners will be added manually by the client-side script.
        'progress' => 'none',
      ),
      '#attributes' => array('class' => array('visually-hidden'))
    );

    $form['actions'] = array('#type' => 'actions');
241
242
243
244
245
    $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#button_type' => 'primary',
      '#value' => $this->t('Save'),
    );
246

247
    $form['#attached']['library'][] = 'field_ui/drupal.field_ui';
248
249
250
251
252
253
254

    return $form;
  }

  /**
   * Builds the table row structure for a single field.
   *
255
256
   * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
   *   The field definition.
257
258
   * @param array $form
   *   An associative array containing the structure of the form.
259
260
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
261
262
263
264
   *
   * @return array
   *   A table row array.
   */
265
  protected function buildFieldRow(FieldDefinitionInterface $field_definition, array $form, FormStateInterface $form_state) {
266
    $field_name = $field_definition->getName();
267
    $display_options = $this->entity->getComponent($field_name);
268
    $label = $field_definition->getLabel();
269

270
271
272
273
274
275
    // Disable fields without any applicable plugins.
    if (empty($this->getApplicablePluginOptions($field_definition))) {
      $this->entity->removeComponent($field_name)->save();
      $display_options = $this->entity->getComponent($field_name);
    }

276
    $regions = array_keys($this->getRegions());
277
278
279
280
281
282
    $field_row = array(
      '#attributes' => array('class' => array('draggable', 'tabledrag-leaf')),
      '#row_type' => 'field',
      '#region_callback' => array($this, 'getRowRegion'),
      '#js_settings' => array(
        'rowHandler' => 'field',
283
        'defaultPlugin' => $this->getDefaultPlugin($field_definition->getType()),
284
285
      ),
      'human_name' => array(
286
        '#plain_text' => $label,
287
288
289
      ),
      'weight' => array(
        '#type' => 'textfield',
290
        '#title' => $this->t('Weight for @title', array('@title' => $label)),
291
292
293
294
295
296
297
298
        '#title_display' => 'invisible',
        '#default_value' => $display_options ? $display_options['weight'] : '0',
        '#size' => 3,
        '#attributes' => array('class' => array('field-weight')),
      ),
      'parent_wrapper' => array(
        'parent' => array(
          '#type' => 'select',
299
          '#title' => $this->t('Label display for @title', array('@title' => $label)),
300
          '#title_display' => 'invisible',
301
          '#options' => array_combine($regions, $regions),
302
          '#empty_value' => '',
303
          '#attributes' => array('class' => array('js-field-parent', 'field-parent')),
304
          '#parents' => array('fields', $field_name, 'parent'),
305
306
307
        ),
        'hidden_name' => array(
          '#type' => 'hidden',
308
          '#default_value' => $field_name,
309
310
311
312
313
314
315
316
          '#attributes' => array('class' => array('field-name')),
        ),
      ),
    );

    $field_row['plugin'] = array(
      'type' => array(
        '#type' => 'select',
317
        '#title' => $this->t('Plugin for @title', array('@title' => $label)),
318
        '#title_display' => 'invisible',
319
        '#options' => $this->getPluginOptions($field_definition),
320
        '#default_value' => $display_options ? $display_options['type'] : 'hidden',
321
        '#parents' => array('fields', $field_name, 'type'),
322
323
324
325
326
327
        '#attributes' => array('class' => array('field-plugin-type')),
      ),
      'settings_edit_form' => array(),
    );

    // Get the corresponding plugin object.
328
    $plugin = $this->entity->getRenderer($field_name);
329
330
331

    // Base button element for the various plugin settings actions.
    $base_button = array(
332
      '#submit' => array('::multistepSubmit'),
333
      '#ajax' => array(
334
        'callback' => '::multistepAjax',
335
336
337
        'wrapper' => 'field-display-overview-wrapper',
        'effect' => 'fade',
      ),
338
      '#field_name' => $field_name,
339
340
    );

341
    if ($form_state->get('plugin_settings_edit') == $field_name) {
342
343
344
345
346
347
348
      // We are currently editing this field's plugin settings. Display the
      // settings form and submit buttons.
      $field_row['plugin']['settings_edit_form'] = array();

      if ($plugin) {
        // Generate the settings form and allow other modules to alter it.
        $settings_form = $plugin->settingsForm($form, $form_state);
349
        $third_party_settings_form = $this->thirdPartySettingsForm($plugin, $field_definition, $form, $form_state);
350

351
        if ($settings_form || $third_party_settings_form) {
352
353
354
355
          $field_row['plugin']['#cell_attributes'] = array('colspan' => 3);
          $field_row['plugin']['settings_edit_form'] = array(
            '#type' => 'container',
            '#attributes' => array('class' => array('field-plugin-settings-edit-form')),
356
            '#parents' => array('fields', $field_name, 'settings_edit_form'),
357
            'label' => array(
358
              '#markup' => $this->t('Plugin settings'),
359
360
            ),
            'settings' => $settings_form,
361
            'third_party_settings' => $third_party_settings_form,
362
363
364
365
            'actions' => array(
              '#type' => 'actions',
              'save_settings' => $base_button + array(
                '#type' => 'submit',
366
                '#button_type' => 'primary',
367
                '#name' => $field_name . '_plugin_settings_update',
368
                '#value' => $this->t('Update'),
369
370
371
372
                '#op' => 'update',
              ),
              'cancel_settings' => $base_button + array(
                '#type' => 'submit',
373
                '#name' => $field_name . '_plugin_settings_cancel',
374
                '#value' => $this->t('Cancel'),
375
376
377
                '#op' => 'cancel',
                // Do not check errors for the 'Cancel' button, but make sure we
                // get the value of the 'plugin type' select.
378
                '#limit_validation_errors' => array(array('fields', $field_name, 'type')),
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
              ),
            ),
          );
          $field_row['#attributes']['class'][] = 'field-plugin-settings-editing';
        }
      }
    }
    else {
      $field_row['settings_summary'] = array();
      $field_row['settings_edit'] = array();

      if ($plugin) {
        // Display a summary of the current plugin settings, and (if the
        // summary is not empty) a button to edit them.
        $summary = $plugin->settingsSummary();

        // Allow other modules to alter the summary.
396
        $this->alterSettingsSummary($summary, $plugin, $field_definition);
397
398
399

        if (!empty($summary)) {
          $field_row['settings_summary'] = array(
400
401
402
            '#type' => 'inline_template',
            '#template' => '<div class="field-plugin-summary">{{ summary|safe_join("<br />") }}</div>',
            '#context' => array('summary' => $summary),
403
404
            '#cell_attributes' => array('class' => array('field-plugin-summary-cell')),
          );
405
        }
406
407

        // Check selected plugin settings to display edit link or not.
408
409
410
        $settings_form = $plugin->settingsForm($form, $form_state);
        $third_party_settings_form = $this->thirdPartySettingsForm($plugin, $field_definition, $form, $form_state);
        if (!empty($settings_form) || !empty($third_party_settings_form)) {
411
412
          $field_row['settings_edit'] = $base_button + array(
            '#type' => 'image_button',
413
            '#name' => $field_name . '_settings_edit',
414
            '#src' => 'core/misc/icons/787878/cog.svg',
415
            '#attributes' => array('class' => array('field-plugin-settings-edit'), 'alt' => $this->t('Edit')),
416
417
418
            '#op' => 'edit',
            // Do not check errors for the 'Edit' button, but make sure we get
            // the value of the 'plugin type' select.
419
            '#limit_validation_errors' => array(array('fields', $field_name, 'type')),
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
            '#prefix' => '<div class="field-plugin-settings-edit-wrapper">',
            '#suffix' => '</div>',
          );
        }
      }
    }

    return $field_row;
  }

  /**
   * Builds the table row structure for a single extra field.
   *
   * @param string $field_id
   *   The field ID.
   * @param array $extra_field
   *   The pseudo-field element.
   *
   * @return array
   *   A table row array.
   */
441
442
  protected function buildExtraFieldRow($field_id, $extra_field) {
    $display_options = $this->entity->getComponent($field_id);
443

444
    $regions = array_keys($this->getRegions());
445
446
447
448
449
450
    $extra_field_row = array(
      '#attributes' => array('class' => array('draggable', 'tabledrag-leaf')),
      '#row_type' => 'extra_field',
      '#region_callback' => array($this, 'getRowRegion'),
      '#js_settings' => array('rowHandler' => 'field'),
      'human_name' => array(
451
        '#markup' => $extra_field['label'],
452
453
454
      ),
      'weight' => array(
        '#type' => 'textfield',
455
        '#title' => $this->t('Weight for @title', array('@title' => $extra_field['label'])),
456
457
458
459
460
461
462
463
        '#title_display' => 'invisible',
        '#default_value' => $display_options ? $display_options['weight'] : 0,
        '#size' => 3,
        '#attributes' => array('class' => array('field-weight')),
      ),
      'parent_wrapper' => array(
        'parent' => array(
          '#type' => 'select',
464
          '#title' => $this->t('Parents for @title', array('@title' => $extra_field['label'])),
465
          '#title_display' => 'invisible',
466
          '#options' => array_combine($regions, $regions),
467
          '#empty_value' => '',
468
          '#attributes' => array('class' => array('js-field-parent', 'field-parent')),
469
470
471
472
473
474
475
476
477
478
479
          '#parents' => array('fields', $field_id, 'parent'),
        ),
        'hidden_name' => array(
          '#type' => 'hidden',
          '#default_value' => $field_id,
          '#attributes' => array('class' => array('field-name')),
        ),
      ),
      'plugin' => array(
        'type' => array(
          '#type' => 'select',
480
          '#title' => $this->t('Visibility for @title', array('@title' => $extra_field['label'])),
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
          '#title_display' => 'invisible',
          '#options' => $this->getExtraFieldVisibilityOptions(),
          '#default_value' => $display_options ? 'visible' : 'hidden',
          '#parents' => array('fields', $field_id, 'type'),
          '#attributes' => array('class' => array('field-plugin-type')),
        ),
      ),
      'settings_summary' => array(),
      'settings_edit' => array(),
    );

    return $extra_field_row;
  }

  /**
   * {@inheritdoc}
   */
498
  public function submitForm(array &$form, FormStateInterface $form_state) {
499
500
501
502
503
504
505
    // If the main "Save" button was submitted while a field settings subform
    // was being edited, update the new incoming settings when rebuilding the
    // entity, just as if the subform's "Update" button had been submitted.
    if ($edit_field = $form_state->get('plugin_settings_edit')) {
      $form_state->set('plugin_settings_update', $edit_field);
    }

506
    parent::submitForm($form, $form_state);
507
    $form_values = $form_state->getValues();
508
509

    // Handle the 'display modes' checkboxes if present.
510
    if ($this->entity->getMode() == 'default' && !empty($form_values['display_modes_custom'])) {
511
512
513
514
515
516
517
518
519
      $display_modes = $this->getDisplayModes();
      $current_statuses = $this->getDisplayStatuses();

      $statuses = array();
      foreach ($form_values['display_modes_custom'] as $mode => $value) {
        if (!empty($value) && empty($current_statuses[$mode])) {
          // If no display exists for the newly enabled view mode, initialize
          // it with those from the 'default' view mode, which were used so
          // far.
520
521
          if (!$this->entityManager->getStorage($this->entity->getEntityTypeId())->load($this->entity->getTargetEntityTypeId() . '.' . $this->entity->getTargetBundle() . '.' . $mode)) {
            $display = $this->getEntityDisplay($this->entity->getTargetEntityTypeId(), $this->entity->getTargetBundle(), 'default')->createCopy($mode);
522
523
524
525
526
            $display->save();
          }

          $display_mode_label = $display_modes[$mode]['label'];
          $url = $this->getOverviewUrl($mode);
527
          drupal_set_message($this->t('The %display_mode mode now uses custom display settings. You might want to <a href=":url">configure them</a>.', ['%display_mode' => $display_mode_label, ':url' => $url->toString()]));
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
        }
        $statuses[$mode] = !empty($value);
      }

      $this->saveDisplayStatuses($statuses);
    }

    drupal_set_message($this->t('Your settings have been saved.'));
  }

  /**
   * {@inheritdoc}
   */
  protected function copyFormValuesToEntity(EntityInterface $entity, array $form, FormStateInterface $form_state) {
    $form_values = $form_state->getValues();

    if ($this->entity instanceof EntityWithPluginCollectionInterface) {
      // Do not manually update values represented by plugin collections.
      $form_values = array_diff_key($form_values, $this->entity->getPluginCollections());
    }
548
549
550
551
552
553

    // Collect data for 'regular' fields.
    foreach ($form['#fields'] as $field_name) {
      $values = $form_values['fields'][$field_name];

      if ($values['type'] == 'hidden') {
554
        $entity->removeComponent($field_name);
555
556
      }
      else {
557
558
559
560
561
562
        $options = $entity->getComponent($field_name);

        // Update field settings only if the submit handler told us to.
        if ($form_state->get('plugin_settings_update') === $field_name) {
          // Only store settings actually used by the selected plugin.
          $default_settings = $this->pluginManager->getDefaultSettings($options['type']);
563
          $options['settings'] = isset($values['settings_edit_form']['settings']) ? array_intersect_key($values['settings_edit_form']['settings'], $default_settings) : [];
564
565
          $options['third_party_settings'] = isset($values['settings_edit_form']['third_party_settings']) ? $values['settings_edit_form']['third_party_settings'] : [];
          $form_state->set('plugin_settings_update', NULL);
566
567
        }

568
569
        $options['type'] = $values['type'];
        $options['weight'] = $values['weight'];
570
571
        // Only formatters have configurable label visibility.
        if (isset($values['label'])) {
572
          $options['label'] = $values['label'];
573
        }
574
        $entity->setComponent($field_name, $options);
575
576
577
578
579
580
      }
    }

    // Collect data for 'extra' fields.
    foreach ($form['#extra'] as $name) {
      if ($form_values['fields'][$name]['type'] == 'hidden') {
581
        $entity->removeComponent($name);
582
583
      }
      else {
584
        $entity->setComponent($name, array(
585
586
587
588
589
590
591
592
593
          'weight' => $form_values['fields'][$name]['weight'],
        ));
      }
    }
  }

  /**
   * Form submission handler for multistep buttons.
   */
594
  public function multistepSubmit($form, FormStateInterface $form_state) {
595
    $trigger = $form_state->getTriggeringElement();
596
597
598
599
600
601
    $op = $trigger['#op'];

    switch ($op) {
      case 'edit':
        // Store the field whose settings are currently being edited.
        $field_name = $trigger['#field_name'];
602
        $form_state->set('plugin_settings_edit', $field_name);
603
604
605
        break;

      case 'update':
606
607
        // Set the field back to 'non edit' mode, and update $this->entity with
        // the new settings fro the next rebuild.
608
        $field_name = $trigger['#field_name'];
609
        $form_state->set('plugin_settings_edit', NULL);
610
611
        $form_state->set('plugin_settings_update', $field_name);
        $this->entity = $this->buildEntity($form, $form_state);
612
613
614
615
        break;

      case 'cancel':
        // Set the field back to 'non edit' mode.
616
        $form_state->set('plugin_settings_edit', NULL);
617
618
619
620
621
        break;

      case 'refresh_table':
        // If the currently edited field is one of the rows to be refreshed, set
        // it back to 'non edit' mode.
622
        $updated_rows = explode(' ', $form_state->getValue('refresh_rows'));
623
624
625
        $plugin_settings_edit = $form_state->get('plugin_settings_edit');
        if ($plugin_settings_edit && in_array($plugin_settings_edit, $updated_rows)) {
          $form_state->set('plugin_settings_edit', NULL);
626
627
628
629
        }
        break;
    }

630
    $form_state->setRebuild();
631
632
633
634
635
  }

  /**
   * Ajax handler for multistep buttons.
   */
636
  public function multistepAjax($form, FormStateInterface $form_state) {
637
    $trigger = $form_state->getTriggeringElement();
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
    $op = $trigger['#op'];

    // Pick the elements that need to receive the ajax-new-content effect.
    switch ($op) {
      case 'edit':
        $updated_rows = array($trigger['#field_name']);
        $updated_columns = array('plugin');
        break;

      case 'update':
      case 'cancel':
        $updated_rows = array($trigger['#field_name']);
        $updated_columns = array('plugin', 'settings_summary', 'settings_edit');
        break;

      case 'refresh_table':
654
        $updated_rows = array_values(explode(' ', $form_state->getValue('refresh_rows')));
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
        $updated_columns = array('settings_summary', 'settings_edit');
        break;
    }

    foreach ($updated_rows as $name) {
      foreach ($updated_columns as $key) {
        $element = &$form['fields'][$name][$key];
        $element['#prefix'] = '<div class="ajax-new-content">' . (isset($element['#prefix']) ? $element['#prefix'] : '');
        $element['#suffix'] = (isset($element['#suffix']) ? $element['#suffix'] : '') . '</div>';
      }
    }

    // Return the whole table.
    return $form['fields'];
  }

671
672
673
674
675
676
677
678
679
680
  /**
   * Performs pre-render tasks on field_ui_table elements.
   *
   * @param array $elements
   *   A structured array containing two sub-levels of elements. Properties
   *   used:
   *   - #tabledrag: The value is a list of $options arrays that are passed to
   *     drupal_attach_tabledrag(). The HTML ID of the table is added to each
   *     $options array.
   *
681
682
   * @return array
   *
683
684
   * @see drupal_render()
   * @see \Drupal\Core\Render\Element\Table::preRenderTable()
685
686
   *
   * @deprecated in Drupal 8.0.0, will be removed before Drupal 9.0.0.
687
688
   */
  public function tablePreRender($elements) {
689
    return FieldUiTable::tablePreRender($elements);
690
691
692
693
694
695
  }

  /**
   * Determines the rendering order of an array representing a tree.
   *
   * Callback for array_reduce() within
696
   * \Drupal\field_ui\Form\EntityDisplayFormBase::tablePreRender().
697
698
   *
   * @deprecated in Drupal 8.0.0, will be removed before Drupal 9.0.0.
699
700
   */
  public function reduceOrder($array, $a) {
701
    return FieldUiTable::reduceOrder($array, $a);
702
703
  }

704
705
706
707
  /**
   * Returns the extra fields of the entity type and bundle used by this form.
   *
   * @return array
708
709
710
   *   An array of extra field info.
   *
   * @see \Drupal\Core\Entity\EntityManagerInterface::getExtraFields()
711
   */
712
  protected function getExtraFields() {
713
    $context = $this->displayContext == 'view' ? 'display' : $this->displayContext;
714
    $extra_fields = $this->entityManager->getExtraFields($this->entity->getTargetEntityTypeId(), $this->entity->getTargetBundle());
715
    return isset($extra_fields[$context]) ? $extra_fields[$context] : array();
716
  }
717

718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
  /**
   * Returns an entity display object to be used by this form.
   *
   * @param string $entity_type_id
   *   The target entity type ID of the entity display.
   * @param string $bundle
   *   The target bundle of the entity display.
   * @param string $mode
   *   A view or form mode.
   *
   * @return \Drupal\Core\Entity\Display\EntityDisplayInterface
   *   An entity display.
   */
  abstract protected function getEntityDisplay($entity_type_id, $bundle, $mode);

733
  /**
734
   * Returns an array of applicable widget or formatter options for a field.
735
   *
736
737
   * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
   *   The field definition.
738
739
   *
   * @return array
740
   *   An array of applicable widget or formatter options.
741
   */
742
  protected function getApplicablePluginOptions(FieldDefinitionInterface $field_definition) {
743
744
745
746
747
748
749
750
    $options = $this->pluginManager->getOptions($field_definition->getType());
    $applicable_options = array();
    foreach ($options as $option => $label) {
      $plugin_class = DefaultFactory::getPluginClass($option, $this->pluginManager->getDefinition($option));
      if ($plugin_class::isApplicable($field_definition)) {
        $applicable_options[$option] = $label;
      }
    }
751
752
753
754
755
756
757
758
759
760
761
762
763
764
    return $applicable_options;
  }

  /**
   * Returns an array of widget or formatter options for a field.
   *
   * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
   *   The field definition.
   *
   * @return array
   *   An array of widget or formatter options.
   */
  protected function getPluginOptions(FieldDefinitionInterface $field_definition) {
    $applicable_options = $this->getApplicablePluginOptions($field_definition);
765
    return $applicable_options + array('hidden' => '- ' . $this->t('Hidden') . ' -');
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
  }

  /**
   * Returns the ID of the default widget or formatter plugin for a field type.
   *
   * @param string $field_type
   *   The field type.
   *
   * @return string
   *   The widget or formatter plugin ID.
   */
  abstract protected function getDefaultPlugin($field_type);

  /**
   * Returns the form or view modes used by this form.
   *
   * @return array
   *   An array of form or view mode info.
   */
  abstract protected function getDisplayModes();

787
788
789
790
791
792
793
794
  /**
   * Returns an array of form or view mode options.
   *
   * @return array
   *   An array of form or view mode options.
   */
  abstract protected function getDisplayModeOptions();

795
796
797
798
799
800
801
802
  /**
   * Returns a link to the form or view mode admin page.
   *
   * @return array
   *   An array of a form element to be rendered as a link.
   */
  abstract protected function getDisplayModesLink();

803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
  /**
   * Returns the region to which a row in the display overview belongs.
   *
   * @param array $row
   *   The row element.
   *
   * @return string|null
   *   The region name this row belongs to.
   */
  public function getRowRegion($row) {
    switch ($row['#row_type']) {
      case 'field':
      case 'extra_field':
        return ($row['plugin']['type']['#value'] == 'hidden' ? 'hidden' : 'content');
    }
  }

  /**
   * Returns an array of visibility options for extra fields.
   *
   * @return array
   *   An array of visibility options.
   */
  protected function getExtraFieldVisibilityOptions() {
    return array(
828
829
      'visible' => $this->t('Visible'),
      'hidden' => '- ' . $this->t('Hidden') . ' -',
830
831
832
    );
  }

833
834
835
  /**
   * Returns entity (form) displays for the current entity display type.
   *
836
   * @return \Drupal\Core\Entity\Display\EntityDisplayInterface[]
837
838
839
840
   *   An array holding entity displays or entity form displays.
   */
  protected function getDisplays() {
    $load_ids = array();
841
    $display_entity_type = $this->entity->getEntityTypeId();
842
843
    $entity_type = $this->entityManager->getDefinition($display_entity_type);
    $config_prefix = $entity_type->getConfigPrefix();
844
    $ids = $this->configFactory()->listAll($config_prefix . '.' . $this->entity->getTargetEntityTypeId() . '.' . $this->entity->getTargetBundle() . '.');
845
846
847
848
849
850
851
    foreach ($ids as $id) {
      $config_id = str_replace($config_prefix . '.', '', $id);
      list(,, $display_mode) = explode('.', $config_id);
      if ($display_mode != 'default') {
        $load_ids[] = $config_id;
      }
    }
852
    return $this->entityManager->getStorage($display_entity_type)->loadMultiple($load_ids);
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
  }

  /**
   * Returns form or view modes statuses for the bundle used by this form.
   *
   * @return array
   *   An array of form or view mode statuses.
   */
  protected function getDisplayStatuses() {
    $display_statuses = array();
    $displays = $this->getDisplays();
    foreach ($displays as $display) {
      $display_statuses[$display->get('mode')] = $display->status();
    }
    return $display_statuses;
  }

  /**
   * Saves the updated display mode statuses.
   *
   * @param array $display_statuses
   *   An array holding updated form or view mode statuses.
   */
  protected function saveDisplayStatuses($display_statuses) {
    $displays = $this->getDisplays();
    foreach ($displays as $display) {
      $display->set('status', $display_statuses[$display->get('mode')]);
      $display->save();
    }
  }

884
885
886
887
888
889
890
891
892
  /**
   * Returns an array containing the table headers.
   *
   * @return array
   *   The table header.
   */
  abstract protected function getTableHeader();

  /**
893
   * Returns the Url object for a specific entity (form) display edit form.
894
895
896
897
   *
   * @param string $mode
   *   The form or view mode.
   *
898
899
   * @return \Drupal\Core\Url
   *   A Url object for the overview route.
900
   */
901
  abstract protected function getOverviewUrl($mode);
902
903

  /**
904
   * Adds the widget or formatter third party settings forms.
905
   *
906
   * @param \Drupal\Core\Field\PluginSettingsInterface $plugin
907
   *   The widget or formatter.
908
909
   * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
   *   The field definition.
910
   * @param array $form
911
   *   The (entire) configuration form array.
912
   * @param \Drupal\Core\Form\FormStateInterface $form_state
913
   *   The form state.
914
915
916
   *
   * @return array
   *   The widget or formatter third party settings form.
917
   */
918
  abstract protected function thirdPartySettingsForm(PluginSettingsInterface $plugin, FieldDefinitionInterface $field_definition, array $form, FormStateInterface $form_state);
919
920
921
922
923
924

  /**
   * Alters the widget or formatter settings summary.
   *
   * @param array $summary
   *   The widget or formatter settings summary.
925
   * @param \Drupal\Core\Field\PluginSettingsInterface $plugin
926
   *   The widget or formatter.
927
928
   * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
   *   The field definition.
929
   */
930
  abstract protected function alterSettingsSummary(array &$summary, PluginSettingsInterface $plugin, FieldDefinitionInterface $field_definition);
931
932

}