AddFormBase.php 30.6 KB
Newer Older
1
2
3
4
5
<?php

namespace Drupal\media_library\Form;

use Drupal\Core\Ajax\AjaxResponse;
6
use Drupal\Core\Ajax\CloseDialogCommand;
7
use Drupal\Core\Ajax\InvokeCommand;
8
9
10
11
12
13
use Drupal\Core\Ajax\ReplaceCommand;
use Drupal\Core\Entity\Entity\EntityFormDisplay;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
14
use Drupal\Core\Url;
15
16
17
18
use Drupal\media\MediaInterface;
use Drupal\media\MediaTypeInterface;
use Drupal\media_library\Ajax\UpdateSelectionCommand;
use Drupal\media_library\MediaLibraryUiBuilder;
19
use Drupal\media_library\OpenerResolverInterface;
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides a base class for creating media items from within the media library.
 *
 * @internal
 *   Media Library is an experimental module and its internal code may be
 *   subject to change in minor releases. External code should not instantiate
 *   or extend this class.
 */
abstract class AddFormBase extends FormBase {

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The media library UI builder.
   *
   * @var \Drupal\media_library\MediaLibraryUiBuilder
   */
  protected $libraryUiBuilder;

  /**
   * The type of media items being created by this form.
   *
   * @var \Drupal\media\MediaTypeInterface
   */
  protected $mediaType;

53
54
55
56
57
58
59
  /**
   * The media view builder.
   *
   * @var \Drupal\Core\Entity\EntityViewBuilderInterface
   */
  protected $viewBuilder;

60
61
62
63
64
65
66
  /**
   * The opener resolver.
   *
   * @var \Drupal\media_library\OpenerResolverInterface
   */
  protected $openerResolver;

67
68
69
70
71
72
73
  /**
   * Constructs a AddFormBase object.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param \Drupal\media_library\MediaLibraryUiBuilder $library_ui_builder
   *   The media library UI builder.
74
75
   * @param \Drupal\media_library\OpenerResolverInterface $opener_resolver
   *   The opener resolver.
76
   */
77
  public function __construct(EntityTypeManagerInterface $entity_type_manager, MediaLibraryUiBuilder $library_ui_builder, OpenerResolverInterface $opener_resolver = NULL) {
78
79
    $this->entityTypeManager = $entity_type_manager;
    $this->libraryUiBuilder = $library_ui_builder;
80
    $this->viewBuilder = $this->entityTypeManager->getViewBuilder('media');
81
82
83
84
85
    if (!$opener_resolver) {
      @trigger_error('The media_library.opener_resolver service must be passed to AddFormBase::__construct(), it is required before Drupal 9.0.0.', E_USER_DEPRECATED);
      $opener_resolver = \Drupal::service('media_library.opener_resolver');
    }
    $this->openerResolver = $opener_resolver;
86
87
88
89
90
91
92
93
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('entity_type.manager'),
94
95
      $container->get('media_library.ui_builder'),
      $container->get('media_library.opener_resolver')
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'media_library_add_form';
  }

  /**
   * Get the media type from the form state.
   *
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current form state.
   *
   * @return \Drupal\media\MediaTypeInterface
   *   The media type.
114
115
116
   *
   * @throws \InvalidArgumentException
   *   If the selected media type does not exist.
117
118
119
120
121
122
   */
  protected function getMediaType(FormStateInterface $form_state) {
    if ($this->mediaType) {
      return $this->mediaType;
    }

123
124
    $state = $this->getMediaLibraryState($form_state);
    $selected_type_id = $state->getSelectedTypeId();
125
126
127
128
129
130
131
132
133
134
135
136
137
    $this->mediaType = $this->entityTypeManager->getStorage('media_type')->load($selected_type_id);

    if (!$this->mediaType) {
      throw new \InvalidArgumentException("The '$selected_type_id' media type does not exist.");
    }

    return $this->mediaType;
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
138
139
140
    // @todo Remove the ID when we can use selectors to replace content via
    //   AJAX in https://www.drupal.org/project/drupal/issues/2821793.
    $form['#prefix'] = '<div id="media-library-add-form-wrapper" class="media-library-add-form-wrapper">';
141
142
143
    $form['#suffix'] = '</div>';
    $form['#attached']['library'][] = 'media_library/style';

144
145
146
147
148
149
150
151
    // The media library is loaded via AJAX, which means that the form action
    // URL defaults to the current URL. However, to add media, we always need to
    // submit the form to the media library URL, not whatever the current URL
    // may be.
    $form['#action'] = Url::fromRoute('media_library.ui', [], [
      'query' => $this->getMediaLibraryState($form_state)->all(),
    ])->toString();

152
153
154
155
156
157
158
    // The form is posted via AJAX. When there are messages set during the
    // validation or submission of the form, the messages need to be shown to
    // the user.
    $form['status_messages'] = [
      '#type' => 'status_messages',
    ];

159
160
161
162
163
164
    $form['#attributes']['class'] = [
      'media-library-add-form',
      'js-media-library-add-form',
    ];

    $added_media = $this->getAddedMediaItems($form_state);
165
166
167
168
169
170
171
172
173
    if (empty($added_media)) {
      $form['#attributes']['class'][] = 'media-library-add-form--without-input';
      $form = $this->buildInputElement($form, $form_state);
    }
    else {
      $form['#attributes']['class'][] = 'media-library-add-form--with-input';

      $form['media'] = [
        '#type' => 'container',
174
175
        '#attributes' => [
          'class' => [
176
            'js-media-library-add-form-added-media',
177
178
179
180
181
182
183
184
185
186
187
            'media-library-add-form__added-media',
          ],
          'aria-label' => $this->t('Added media items'),
          'role' => 'list',
          // Add the tabindex '-1' to allow the focus to be shifted to the added
          // media wrapper when items are added. We set focus to the container
          // because a media item does not necessarily have required fields and
          // we do not want to set focus to the remove button automatically.
          // @see ::updateFormCallback()
          'tabindex' => '-1',
        ],
188
189
      ];

190
191
192
193
194
195
196
197
198
199
200
      $form['media']['description'] = [
        '#type' => 'html_tag',
        '#tag' => 'p',
        '#value' => $this->formatPlural(count($added_media), 'The media item has been created but has not yet been saved. Fill in any required fields and save to add it to the media library.', 'The media items have been created but have not yet been saved. Fill in any required fields and save to add them to the media library.'),
        '#attributes' => [
          'class' => [
            'media-library-add-form__description',
          ],
        ],
      ];

201
202
203
204
      foreach ($added_media as $delta => $media) {
        $form['media'][$delta] = $this->buildEntityFormElement($media, $form, $form_state, $delta);
      }

205
      $form['selection'] = $this->buildCurrentSelectionArea($form, $form_state);
206
207
      $form['actions'] = $this->buildActions($form, $form_state);
    }
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222

    // Allow the current selection to be set in a hidden field so the selection
    // can be passed between different states of the form. This field is filled
    // via JavaScript so the default value should be empty.
    // @see Drupal.behaviors.MediaLibraryItemSelection
    $form['current_selection'] = [
      '#type' => 'hidden',
      '#default_value' => '',
      '#attributes' => [
        'class' => [
          'js-media-library-add-form-current-selection',
        ],
      ],
    ];

223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
    return $form;
  }

  /**
   * Builds the element for submitting source field value(s).
   *
   * The input element needs to have a submit handler to create media items from
   * the user input and store them in the form state using
   * ::processInputValues().
   *
   * @param array $form
   *   The complete form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current form state.
   *
   * @return array
   *   The complete form, with the element added.
   *
   * @see ::processInputValues()
   */
  abstract protected function buildInputElement(array $form, FormStateInterface $form_state);

  /**
   * Builds the sub-form for setting required fields on a new media item.
   *
   * @param \Drupal\media\MediaInterface $media
   *   A new, unsaved media item.
   * @param array $form
   *   The complete form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current form state.
   * @param int $delta
   *   The delta of the media item.
   *
   * @return array
   *   The element containing the required fields sub-form.
   */
  protected function buildEntityFormElement(MediaInterface $media, array $form, FormStateInterface $form_state, $delta) {
261
262
263
264
265
    // We need to make sure each button has a unique name attribute. The default
    // name for button elements is 'op'. If the name is not unique, the
    // triggering element is not set correctly and the wrong media item is
    // removed.
    // @see ::removeButtonSubmit()
266
    $parents = isset($form['#parents']) ? $form['#parents'] : [];
267
268
    $id_suffix = $parents ? '-' . implode('-', $parents) : '';

269
270
271
272
273
274
    $element = [
      '#type' => 'container',
      '#attributes' => [
        'class' => [
          'media-library-add-form__media',
        ],
275
276
277
278
279
280
281
282
283
284
285
286
        'aria-label' => $media->getName(),
        'role' => 'listitem',
        // Add the tabindex '-1' to allow the focus to be shifted to the next
        // media item when an item is removed. We set focus to the container
        // because a media item does not necessarily have required fields and we
        // do not want to set focus to the remove button automatically.
        // @see ::updateFormCallback()
        'tabindex' => '-1',
        // Add a data attribute containing the delta to allow us to easily shift
        // the focus to a specific media item.
        // @see ::updateFormCallback()
        'data-media-library-added-delta' => $delta,
287
288
289
      ],
      'preview' => [
        '#type' => 'container',
290
        '#weight' => 10,
291
292
293
294
295
296
297
298
        '#attributes' => [
          'class' => [
            'media-library-add-form__preview',
          ],
        ],
      ],
      'fields' => [
        '#type' => 'container',
299
        '#weight' => 20,
300
301
302
303
304
305
306
307
308
        '#attributes' => [
          'class' => [
            'media-library-add-form__fields',
          ],
        ],
        // The '#parents' are set here because the entity form display needs it
        // to build the entity form fields.
        '#parents' => ['media', $delta, 'fields'],
      ],
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
      'remove_button' => [
        '#type' => 'submit',
        '#value' => $this->t('Remove'),
        '#name' => 'media-' . $delta . '-remove-button' . $id_suffix,
        '#weight' => 30,
        '#attributes' => [
          'class' => ['media-library-add-form__remove-button'],
          'aria-label' => $this->t('Remove @label', ['@label' => $media->getName()]),
        ],
        '#ajax' => [
          'callback' => '::updateFormCallback',
          'wrapper' => 'media-library-add-form-wrapper',
          'message' => $this->t('Removing @label.', ['@label' => $media->getName()]),
        ],
        '#submit' => ['::removeButtonSubmit'],
        // Ensure errors in other media items do not prevent removal.
        '#limit_validation_errors' => [],
      ],
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
    ];
    // @todo Make the image style configurable in
    //   https://www.drupal.org/node/2988223
    $source = $media->getSource();
    $plugin_definition = $source->getPluginDefinition();
    if ($thumbnail_uri = $source->getMetadata($media, $plugin_definition['thumbnail_uri_metadata_attribute'])) {
      $element['preview']['thumbnail'] = [
        '#theme' => 'image_style',
        '#style_name' => 'media_library',
        '#uri' => $thumbnail_uri,
      ];
    }

    $form_display = EntityFormDisplay::collectRenderDisplay($media, 'media_library');
    // When the name is not added to the form as an editable field, output
    // the name as a fixed element to confirm the right file was uploaded.
    if (!$form_display->getComponent('name')) {
      $element['fields']['name'] = [
        '#type' => 'item',
        '#title' => $this->t('Name'),
        '#markup' => $media->getName(),
      ];
    }
    $form_display->buildForm($media, $element['fields'], $form_state);

    // We hide the preview of the uploaded file in the image widget with CSS.
    // @todo Improve hiding file widget elements in
    //   https://www.drupal.org/project/drupal/issues/2987921
    $source_field_name = $this->getSourceFieldName($media->bundle->entity);
    if (isset($element['fields'][$source_field_name])) {
      $element['fields'][$source_field_name]['#attributes']['class'][] = 'media-library-add-form__source-field';
    }
    // The revision log field is currently not configurable from the form
    // display, so hide it by changing the access.
    // @todo Make the revision_log_message field configurable in
    //   https://www.drupal.org/project/drupal/issues/2696555
    if (isset($element['fields']['revision_log_message'])) {
      $element['fields']['revision_log_message']['#access'] = FALSE;
    }
    return $element;
  }

369
370
371
372
373
374
375
376
377
378
379
380
381
382
  /**
   * Returns a render array containing the current selection.
   *
   * @param array $form
   *   The complete form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current form state.
   *
   * @return array
   *   A render array containing the current selection.
   */
  protected function buildCurrentSelectionArea(array $form, FormStateInterface $form_state) {
    $pre_selected_items = $this->getPreSelectedMediaItems($form_state);

383
    if (!$pre_selected_items || !$this->isAdvancedUi()) {
384
385
386
387
388
389
390
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
      return [];
    }

    $selection = [
      '#type' => 'details',
      '#open' => FALSE,
      '#title' => $this->t('Additional selected media'),
      '#attributes' => [
        'class' => [
          'media-library-add-form__selected-media',
        ],
      ],
    ];
    foreach ($pre_selected_items as $media_id => $media) {
      $selection[$media_id] = $this->buildSelectedItemElement($media, $form, $form_state);
    }

    return $selection;
  }

  /**
   * Returns a render array for a single pre-selected media item.
   *
   * @param \Drupal\media\MediaInterface $media
   *   The media item.
   * @param array $form
   *   The complete form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current form state.
   *
   * @return array
   *   A render array of a pre-selected media item.
   */
  protected function buildSelectedItemElement(MediaInterface $media, array $form, FormStateInterface $form_state) {
    return [
      '#type' => 'container',
      '#attributes' => [
        'class' => [
          'media-library-item',
          'media-library-item--grid',
          'media-library-item--small',
          'js-media-library-item',
          'js-click-to-select',
        ],
      ],
      'select' => [
        '#type' => 'container',
        '#attributes' => [
          'class' => [
433
            'js-click-to-select-checkbox media-library-item__click-to-select-checkbox',
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
          ],
        ],
        'select_checkbox' => [
          '#type' => 'checkbox',
          '#title' => $this->t('Select @name', ['@name' => $media->label()]),
          '#title_display' => 'invisible',
          '#return_value' => $media->id(),
          // The checkbox's value is never processed by this form. It is present
          // for usability and accessibility reasons, and only used by
          // JavaScript to track whether or not this media item is selected. The
          // hidden 'current_selection' field is used to store the actual IDs of
          // selected media items.
          '#value' => FALSE,
        ],
      ],
      'rendered_entity' => $this->viewBuilder->view($media, 'media_library'),
    ];
  }

453
454
455
456
457
458
459
460
461
462
463
464
  /**
   * Returns an array of supported actions for the form.
   *
   * @param array $form
   *   The complete form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current form state.
   *
   * @return array
   *   An actions element containing the actions of the form.
   */
  protected function buildActions(array $form, FormStateInterface $form_state) {
465
    $actions = [
466
      '#type' => 'actions',
467
      'save_select' => [
468
        '#type' => 'submit',
469
        '#button_type' => 'primary',
470
        '#value' => $this->t('Save'),
471
472
473
474
475
        '#ajax' => [
          'callback' => '::updateLibrary',
          'wrapper' => 'media-library-add-form-wrapper',
        ],
      ],
476
    ];
477
478
479
480
481
482
483
484
485
486
487
488
489
490
    if ($this->isAdvancedUi()) {
      $actions['save_select']['#value'] = $this->t('Save and select');
      $actions['save_insert'] = [
        'save_insert' => [
          '#type' => 'submit',
          '#value' => $this->t('Save and insert'),
          '#ajax' => [
            'callback' => '::updateWidget',
            'wrapper' => 'media-library-add-form-wrapper',
          ],
        ],
      ];
    }
    return $actions;
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
  }

  /**
   * Creates media items from source field input values.
   *
   * @param mixed[] $source_field_values
   *   The values for source fields of the media items.
   * @param array $form
   *   The complete form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current form state.
   */
  protected function processInputValues(array $source_field_values, array $form, FormStateInterface $form_state) {
    $media_type = $this->getMediaType($form_state);
    $media_storage = $this->entityTypeManager->getStorage('media');
    $source_field_name = $this->getSourceFieldName($media_type);
    $media = array_map(function ($source_field_value) use ($media_type, $media_storage, $source_field_name) {
      return $this->createMediaFromValue($media_type, $media_storage, $source_field_name, $source_field_value);
    }, $source_field_values);
510
    // Re-key the media items before setting them in the form state.
511
512
513
514
515
    $form_state->set('media', array_values($media));
    // Save the selected items in the form state so they are remembered when an
    // item is removed.
    $form_state->set('current_selection', array_filter(explode(',', $form_state->getValue('current_selection'))));
    $form_state->setRebuild();
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
  }

  /**
   * Creates a new, unsaved media item from a source field value.
   *
   * @param \Drupal\media\MediaTypeInterface $media_type
   *   The media type of the media item.
   * @param \Drupal\Core\Entity\EntityStorageInterface $media_storage
   *   The media storage.
   * @param string $source_field_name
   *   The name of the media type's source field.
   * @param mixed $source_field_value
   *   The value for the source field of the media item.
   *
   * @return \Drupal\media\MediaInterface
   *   An unsaved media entity.
   */
  protected function createMediaFromValue(MediaTypeInterface $media_type, EntityStorageInterface $media_storage, $source_field_name, $source_field_value) {
534
    $media = $media_storage->create([
535
536
537
      'bundle' => $media_type->id(),
      $source_field_name => $source_field_value,
    ]);
538
539
    $media->setName($media->getName());
    return $media;
540
541
542
543
544
545
546
547
548
549
550
551
  }

  /**
   * Prepares a created media item to be permanently saved.
   *
   * @param \Drupal\media\MediaInterface $media
   *   The unsaved media item.
   */
  protected function prepareMediaEntityForSave(MediaInterface $media) {
    // Intentionally empty by default.
  }

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
  /**
   * Submit handler for the remove button.
   *
   * @param array $form
   *   The form render array.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   */
  public function removeButtonSubmit(array $form, FormStateInterface $form_state) {
    // Retrieve the delta of the media item from the parents of the remove
    // button.
    $triggering_element = $form_state->getTriggeringElement();
    $delta = array_slice($triggering_element['#array_parents'], -2, 1)[0];

    $added_media = $form_state->get('media');
    $removed_media = $added_media[$delta];

    // Update the list of added media items in the form state.
    unset($added_media[$delta]);

    // Update the media items in the form state.
    $form_state->set('media', $added_media)->setRebuild();

    // Show a message to the user to confirm the media is removed.
    $this->messenger()->addStatus($this->t('The media item %label has been removed.', ['%label' => $removed_media->label()]));
  }

579
580
581
582
583
584
585
586
587
588
589
590
  /**
   * AJAX callback to update the entire form based on source field input.
   *
   * @param array $form
   *   The complete form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current form state.
   *
   * @return \Drupal\Core\Ajax\AjaxResponse|array
   *   The form render array or an AJAX response object.
   */
  public function updateFormCallback(array &$form, FormStateInterface $form_state) {
591
592
593
594
595
596
    $triggering_element = $form_state->getTriggeringElement();
    $wrapper_id = $triggering_element['#ajax']['wrapper'];
    $added_media = $form_state->get('media');

    $response = new AjaxResponse();

597
598
599
600
601
602
603
604
605
    // When the source field input contains errors, replace the existing form to
    // let the user change the source field input. If the user input is valid,
    // the entire modal is replaced with the second step of the form to show the
    // form fields for each media item.
    if ($form_state::hasAnyErrors()) {
      $response->addCommand(new ReplaceCommand('#media-library-add-form-wrapper', $form));
      return $response;
    }

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
    // Check if the remove button is clicked.
    if (end($triggering_element['#parents']) === 'remove_button') {
      // When the list of added media is empty, return to the media library and
      // shift focus back to the first tabbable element (which should be the
      // source field).
      if (empty($added_media)) {
        $response->addCommand(new ReplaceCommand('#media-library-add-form-wrapper', $this->buildMediaLibraryUi($form_state)));
        $response->addCommand(new InvokeCommand('#media-library-add-form-wrapper :tabbable', 'focus'));
      }
      // When there are still more items, update the form and shift the focus to
      // the next media item. If the last list item is removed, shift focus to
      // the previous item.
      else {
        $response->addCommand(new ReplaceCommand("#$wrapper_id", $form));

        // Find the delta of the next media item. If there is no item with a
        // bigger delta, we automatically use the delta of the previous item and
        // shift the focus there.
        $removed_delta = array_slice($triggering_element['#array_parents'], -2, 1)[0];
        $delta_to_focus = 0;
        foreach ($added_media as $delta => $media) {
          $delta_to_focus = $delta;
          if ($delta > $removed_delta) {
            break;
          }
        }
        $response->addCommand(new InvokeCommand(".media-library-add-form__media[data-media-library-added-delta=$delta_to_focus]", 'focus'));
      }
    }
    // Update the form and shift focus to the added media items.
    else {
      $response->addCommand(new ReplaceCommand("#$wrapper_id", $form));
      $response->addCommand(new InvokeCommand('.media-library-add-form__added-media', 'focus'));
    }

    return $response;
642
643
644
645
646
647
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
648
    foreach ($this->getAddedMediaItems($form_state) as $delta => $media) {
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
      $this->validateMediaEntity($media, $form, $form_state, $delta);
    }
  }

  /**
   * Validate a created media item.
   *
   * @param \Drupal\media\MediaInterface $media
   *   The media item to validate.
   * @param array $form
   *   The complete form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current form state.
   * @param int $delta
   *   The delta of the media item.
   */
  protected function validateMediaEntity(MediaInterface $media, array $form, FormStateInterface $form_state, $delta) {
    $form_display = EntityFormDisplay::collectRenderDisplay($media, 'media_library');
    $form_display->extractFormValues($media, $form['media'][$delta]['fields'], $form_state);
    $form_display->validateFormValues($media, $form['media'][$delta]['fields'], $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
675
    foreach ($this->getAddedMediaItems($form_state) as $delta => $media) {
676
677
678
679
680
681
682
683
      EntityFormDisplay::collectRenderDisplay($media, 'media_library')
        ->extractFormValues($media, $form['media'][$delta]['fields'], $form_state);
      $this->prepareMediaEntityForSave($media);
      $media->save();
    }
  }

  /**
684
   * AJAX callback to send the new media item(s) to the media library.
685
686
687
688
689
690
691
   *
   * @param array $form
   *   The complete form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current form state.
   *
   * @return array|\Drupal\Core\Ajax\AjaxResponse
692
693
   *   The form array if there are validation errors, or an AJAX response to add
   *   the created items to the current selection.
694
   */
695
  public function updateLibrary(array &$form, FormStateInterface $form_state) {
696
697
698
699
700
701
    if ($form_state::hasAnyErrors()) {
      return $form;
    }

    $media_ids = array_map(function (MediaInterface $media) {
      return $media->id();
702
    }, $this->getAddedMediaItems($form_state));
703

704
705
    $response = new AjaxResponse();
    $response->addCommand(new UpdateSelectionCommand($media_ids));
706
    $media_id_to_focus = array_pop($media_ids);
707
    $response->addCommand(new ReplaceCommand('#media-library-add-form-wrapper', $this->buildMediaLibraryUi($form_state)));
708
    $response->addCommand(new InvokeCommand("#media-library-content [value=$media_id_to_focus]", 'focus'));
709
710
711
712
713
714
715
716
717
718
719
720
721
    return $response;
  }

  /**
   * Build the render array of the media library UI.
   *
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current form state.
   *
   * @return array
   *   The render array for the media library.
   */
  protected function buildMediaLibraryUi(FormStateInterface $form_state) {
722
723
724
725
726
727
    // Get the render array for the media library. The media library state might
    // contain the 'media_library_content' when it has been opened from a
    // vertical tab. We need to remove that to make sure the render array
    // contains the vertical tabs. Besides that, we also need to force the media
    // library to create a new instance of the media add form.
    // @see \Drupal\media_library\MediaLibraryUiBuilder::buildMediaTypeAddForm()
728
    $state = $this->getMediaLibraryState($form_state);
729
730
    $state->remove('media_library_content');
    $state->set('_media_library_form_rebuild', TRUE);
731
    return $this->libraryUiBuilder->buildUi($state);
732
733
  }

734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
  /**
   * AJAX callback to send the new media item(s) to the calling code.
   *
   * @param array $form
   *   The complete form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current form state.
   *
   * @return array|\Drupal\Core\Ajax\AjaxResponse
   *   The form array when there are form errors or a AJAX response to select
   *   the created items in the media library.
   */
  public function updateWidget(array &$form, FormStateInterface $form_state) {
    if ($form_state::hasAnyErrors()) {
      return $form;
    }

751
752
753
754
755
756
757
758
759
760
761
762
    // The added media items get an ID when they are saved in ::submitForm().
    // For that reason the added media items are keyed by delta in the form
    // state and we have to do an array map to get each media ID.
    $current_media_ids = array_map(function (MediaInterface $media) {
      return $media->id();
    }, $this->getCurrentMediaItems($form_state));

    // Allow the opener service to respond to the selection.
    $state = $this->getMediaLibraryState($form_state);
    return $this->openerResolver->get($state)
      ->getSelectionResponse($state, $current_media_ids)
      ->addCommand(new CloseDialogCommand());
763
764
  }

765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
  /**
   * Get the media library state from the form state.
   *
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current form state.
   *
   * @return \Drupal\media_library\MediaLibraryState
   *   The media library state.
   *
   * @throws \InvalidArgumentException
   *   If the media library state is not present in the form state.
   */
  protected function getMediaLibraryState(FormStateInterface $form_state) {
    $state = $form_state->get('media_library_state');
    if (!$state) {
      throw new \InvalidArgumentException('The media library state is not present in the form state.');
    }
    return $state;
  }

785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
  /**
   * Returns the name of the source field for a media type.
   *
   * @param \Drupal\media\MediaTypeInterface $media_type
   *   The media type to get the source field name for.
   *
   * @return string
   *   The name of the media type's source field.
   */
  protected function getSourceFieldName(MediaTypeInterface $media_type) {
    return $media_type->getSource()
      ->getSourceFieldDefinition($media_type)
      ->getName();
  }

800
801
802
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
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
  /**
   * Get all pre-selected media items from the form state.
   *
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current form state.
   *
   * @return \Drupal\media\MediaInterface[]
   *   An array containing the pre-selected media items keyed by ID.
   */
  protected function getPreSelectedMediaItems(FormStateInterface $form_state) {
    // Get the current selection from the form state.
    // @see ::processInputValues()
    $media_ids = $form_state->get('current_selection');
    if (!$media_ids) {
      return [];
    }
    return $this->entityTypeManager->getStorage('media')->loadMultiple($media_ids);
  }

  /**
   * Get all added media items from the form state.
   *
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current form state.
   *
   * @return \Drupal\media\MediaInterface[]
   *   An array containing the added media items keyed by delta. The media items
   *   won't have an ID untill they are saved in ::submitForm().
   */
  protected function getAddedMediaItems(FormStateInterface $form_state) {
    return $form_state->get('media') ?: [];
  }

  /**
   * Get all pre-selected and added media items from the form state.
   *
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current form state.
   *
   * @return \Drupal\media\MediaInterface[]
   *   An array containing all pre-selected and added media items with
   *   renumbered numeric keys.
   */
  protected function getCurrentMediaItems(FormStateInterface $form_state) {
    $pre_selected_media = $this->getPreSelectedMediaItems($form_state);
    $added_media = $this->getAddedMediaItems($form_state);
    // Using array_merge will renumber the numeric keys.
    return array_merge($pre_selected_media, $added_media);
  }

850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
  /**
   * Determines if the "advanced UI" of the Media Library is enabled.
   *
   * This exposes additional features that are useful to power users.
   *
   * @return bool
   *   TRUE if the advanced UI is enabled, FALSE otherwise.
   *
   * @see ::buildActions()
   * @see ::buildCurrentSelectionArea()
   */
  protected function isAdvancedUi() {
    return (bool) $this->config('media_library.settings')->get('advanced_ui');
  }

865
}