summaryrefslogtreecommitdiffstats
path: root/core/modules/media/src/MediaTypeForm.php
blob: 9ae84e9baaf4600becb069888217fc2f9bc81b7b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
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
369
370
371
372
373
374
375
376
<?php

namespace Drupal\media;

use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\ReplaceCommand;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Entity\EntityForm;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Form\SubformState;
use Drupal\language\Entity\ContentLanguageSettings;
use Drupal\media\Entity\MediaType;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Form controller for media type forms.
 */
class MediaTypeForm extends EntityForm {

  /**
   * Media source plugin manager.
   *
   * @var \Drupal\media\MediaSourceManager
   */
  protected $sourceManager;

  /**
   * Entity field manager service.
   *
   * @var \Drupal\Core\Entity\EntityFieldManagerInterface
   */
  protected $entityFieldManager;

  /**
   * Constructs a new class instance.
   *
   * @param \Drupal\media\MediaSourceManager $source_manager
   *   Media source plugin manager.
   * @param \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager
   *   Entity field manager service.
   */
  public function __construct(MediaSourceManager $source_manager, EntityFieldManagerInterface $entity_field_manager) {
    $this->sourceManager = $source_manager;
    $this->entityFieldManager = $entity_field_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('plugin.manager.media.source'),
      $container->get('entity_field.manager')
    );
  }

  /**
   * Ajax callback triggered by the type provider select element.
   */
  public function ajaxHandlerData(array $form, FormStateInterface $form_state) {
    $response = new AjaxResponse();
    $response->addCommand(new ReplaceCommand('#source-dependent', $form['source_dependent']));
    return $response;
  }

  /**
   * {@inheritdoc}
   */
  public function form(array $form, FormStateInterface $form_state) {
    $form = parent::form($form, $form_state);

    // Source is not set when the entity is initially created.
    /** @var \Drupal\media\MediaSourceInterface $source */
    $source = $this->entity->get('source') ? $this->entity->getSource() : NULL;

    if ($this->operation === 'add') {
      $form['#title'] = $this->t('Add media type');
    }

    $form['label'] = [
      '#title' => $this->t('Name'),
      '#type' => 'textfield',
      '#default_value' => $this->entity->label(),
      '#description' => $this->t('The human-readable name of this media type.'),
      '#required' => TRUE,
      '#size' => 30,
    ];

    $form['id'] = [
      '#type' => 'machine_name',
      '#default_value' => $this->entity->id(),
      '#maxlength' => 32,
      '#disabled' => !$this->entity->isNew(),
      '#machine_name' => [
        'exists' => [MediaType::class, 'load'],
      ],
      '#description' => $this->t('A unique machine-readable name for this media type.'),
    ];

    $form['description'] = [
      '#title' => $this->t('Description'),
      '#type' => 'textarea',
      '#default_value' => $this->entity->getDescription(),
      '#description' => $this->t('Describe this media type. The text will be displayed on the <em>Add new media</em> page.'),
    ];

    $plugins = $this->sourceManager->getDefinitions();
    $options = [];
    foreach ($plugins as $plugin_id => $definition) {
      $options[$plugin_id] = $definition['label'];
    }

    $form['source_dependent'] = [
      '#type' => 'container',
      '#attributes' => ['id' => 'source-dependent'],
    ];

    $form['source_dependent']['source'] = [
      '#type' => 'select',
      '#title' => $this->t('Media source'),
      '#default_value' => $source ? $source->getPluginId() : NULL,
      '#options' => $options,
      '#description' => $this->t('Media source that is responsible for additional logic related to this media type.'),
      '#ajax' => ['callback' => '::ajaxHandlerData'],
      '#required' => TRUE,
    ];

    if (!$source) {
      $form['type']['#empty_option'] = $this->t('- Select media source -');
    }

    if ($source) {
      // Media source plugin configuration.
      $form['source_dependent']['source_configuration'] = [
        '#type' => 'fieldset',
        '#title' => $this->t('Media source configuration'),
        '#tree' => TRUE,
      ];

      $form['source_dependent']['source_configuration'] = $source->buildConfigurationForm($form['source_dependent']['source_configuration'], $this->getSourceSubFormState($form, $form_state));
    }

    // Field mapping configuration.
    $form['source_dependent']['field_map'] = [
      '#type' => 'fieldset',
      '#title' => $this->t('Field mapping'),
      '#tree' => TRUE,
      'description' => [
        '#markup' => '<p>' . $this->t('Media sources can provide metadata fields such as title, caption, size information, credits, etc. Media can automatically save this metadata information to entity fields, which can be configured below. Information will only be mapped if the entity field is empty.') . '</p>',
      ],
    ];

    if (empty($source) || empty($source->getMetadataAttributes())) {
      $form['source_dependent']['field_map']['#access'] = FALSE;
    }
    else {
      $options = [MediaSourceInterface::METADATA_FIELD_EMPTY => $this->t('- Skip field -')];
      foreach ($this->entityFieldManager->getFieldDefinitions('media', $this->entity->id()) as $field_name => $field) {
        if (!($field instanceof BaseFieldDefinition) || $field_name === 'name') {
          $options[$field_name] = $field->getLabel();
        }
      }

      $field_map = $this->entity->getFieldMap();
      foreach ($source->getMetadataAttributes() as $metadata_attribute_name => $metadata_attribute_label) {
        $form['source_dependent']['field_map'][$metadata_attribute_name] = [
          '#type' => 'select',
          '#title' => $metadata_attribute_label,
          '#options' => $options,
          '#default_value' => isset($field_map[$metadata_attribute_name]) ? $field_map[$metadata_attribute_name] : MediaSourceInterface::METADATA_FIELD_EMPTY,
        ];
      }
    }

    $form['additional_settings'] = [
      '#type' => 'vertical_tabs',
      '#attached' => [
        'library' => ['media/media_type_form'],
      ],
    ];

    $form['workflow'] = [
      '#type' => 'details',
      '#title' => $this->t('Publishing options'),
      '#group' => 'additional_settings',
    ];

    $form['workflow']['options'] = [
      '#type' => 'checkboxes',
      '#title' => $this->t('Default options'),
      '#default_value' => $this->getWorkflowOptions(),
      '#options' => [
        'status' => $this->t('Published'),
        'new_revision' => $this->t('Create new revision'),
        'queue_thumbnail_downloads' => $this->t('Queue thumbnail downloads'),
      ],
    ];

    $form['workflow']['options']['status']['#description'] = $this->t('Media will be automatically published when created.');
    $form['workflow']['options']['new_revision']['#description'] = $this->t('Automatically create new revisions. Users with the "Administer media" permission will be able to override this option.');
    $form['workflow']['options']['queue_thumbnail_downloads']['#description'] = $this->t('Download thumbnails via a queue. When using remote media sources, the thumbnail generation could be a slow process. Using a queue allows for this process to be handled in the background.');

    if ($this->moduleHandler->moduleExists('language')) {
      $form['language'] = [
        '#type' => 'details',
        '#title' => $this->t('Language settings'),
        '#group' => 'additional_settings',
      ];

      $language_configuration = ContentLanguageSettings::loadByEntityTypeBundle('media', $this->entity->id());
      $form['language']['language_configuration'] = [
        '#type' => 'language_configuration',
        '#entity_information' => [
          'entity_type' => 'media',
          'bundle' => $this->entity->id(),
        ],
        '#default_value' => $language_configuration,
      ];
    }

    return $form;
  }

  /**
   * Prepares workflow options to be used in the 'checkboxes' form element.
   *
   * @return array
   *   Array of options ready to be used in #options.
   */
  protected function getWorkflowOptions() {
    $workflow_options = [
      'status' => $this->entity->getStatus(),
      'new_revision' => $this->entity->shouldCreateNewRevision(),
      'queue_thumbnail_downloads' => $this->entity->thumbnailDownloadsAreQueued(),
    ];
    // Prepare workflow options to be used for 'checkboxes' form element.
    $keys = array_keys(array_filter($workflow_options));
    return array_combine($keys, $keys);
  }

  /**
   * Gets subform state for the media source configuration subform.
   *
   * @param array $form
   *   Full form array.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   Parent form state.
   *
   * @return \Drupal\Core\Form\SubformStateInterface
   *   Sub-form state for the media source configuration form.
   */
  protected function getSourceSubFormState(array $form, FormStateInterface $form_state) {
    return SubformState::createForSubform($form['source_dependent']['source_configuration'], $form, $form_state)
      ->set('operation', $this->operation)
      ->set('type', $this->entity);
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    parent::validateForm($form, $form_state);

    if ($form['source_dependent']['source_configuration']) {
      // Let the selected plugin validate its settings.
      $this->entity->getSource()->validateConfigurationForm($form['source_dependent']['source_configuration'], $this->getSourceSubFormState($form, $form_state));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $form_state->setValue('field_map', array_filter(
      $form_state->getValue('field_map', []),
      function ($item) {
        return $item != MediaSourceInterface::METADATA_FIELD_EMPTY;
      }
    ));

    parent::submitForm($form, $form_state);

    $this->entity->setQueueThumbnailDownloadsStatus((bool) $form_state->getValue(['options', 'queue_thumbnail_downloads']))
      ->setStatus((bool) $form_state->getValue(['options', 'status']))
      ->setNewRevision((bool) $form_state->getValue(['options', 'new_revision']));

    if ($form['source_dependent']['source_configuration']) {
      // Let the selected plugin save its settings.
      $this->entity->getSource()->submitConfigurationForm($form['source_dependent']['source_configuration'], $this->getSourceSubFormState($form, $form_state));
    }
  }

  /**
   * {@inheritdoc}
   */
  protected function actions(array $form, FormStateInterface $form_state) {
    $actions = parent::actions($form, $form_state);
    $actions['submit']['#value'] = $this->t('Save');
    $actions['delete']['#value'] = $this->t('Delete');
    $actions['delete']['#access'] = $this->entity->access('delete');
    return $actions;
  }

  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state) {
    $status = parent::save($form, $form_state);
    /** @var \Drupal\media\MediaTypeInterface $media_type */
    $media_type = $this->entity;

    // If the media source is using a source field, ensure it's
    // properly created.
    $source = $media_type->getSource();
    $source_field = $source->getSourceFieldDefinition($media_type);
    if (!$source_field) {
      $source_field = $source->createSourceField($media_type);
      /** @var \Drupal\field\FieldStorageConfigInterface $storage */
      $storage = $source_field->getFieldStorageDefinition();
      if ($storage->isNew() || !$storage->isLocked()) {
        $storage->setLocked(TRUE)->save();
      }
      $source_field->save();

      // Add the new field to the default form and view displays for this
      // media type.
      $field_name = $source_field->getName();
      $field_type = $source_field->getType();

      if ($source_field->isDisplayConfigurable('form')) {
        // Use the default widget and settings.
        $component = \Drupal::service('plugin.manager.field.widget')
          ->prepareConfiguration($field_type, []);

        // @todo Replace entity_get_form_display() when #2367933 is done.
        // https://www.drupal.org/node/2872159.
        entity_get_form_display('media', $media_type->id(), 'default')
          ->setComponent($field_name, $component)
          ->save();
      }
      if ($source_field->isDisplayConfigurable('view')) {
        // Use the default formatter and settings.
        $component = \Drupal::service('plugin.manager.field.formatter')
          ->prepareConfiguration($field_type, []);

        // @todo Replace entity_get_display() when #2367933 is done.
        // https://www.drupal.org/node/2872159.
        entity_get_display('media', $media_type->id(), 'default')
          ->setComponent($field_name, $component)
          ->save();
      }
    }

    $t_args = ['%name' => $media_type->label()];
    if ($status === SAVED_UPDATED) {
      drupal_set_message($this->t('The media type %name has been updated.', $t_args));
    }
    elseif ($status === SAVED_NEW) {
      drupal_set_message($this->t('The media type %name has been added.', $t_args));
      $this->logger('media')->notice('Added media type %name.', $t_args);
    }

    // Override the "status" base field default value, for this media type.
    $fields = $this->entityFieldManager->getFieldDefinitions('media', $media_type->id());
    /** @var \Drupal\media\MediaInterface $media */
    $media = $this->entityTypeManager->getStorage('media')->create(['bundle' => $media_type->id()]);
    $value = (bool) $form_state->getValue(['options', 'status']);
    if ($media->status->value != $value) {
      $fields['status']->getConfig($media_type->id())->setDefaultValue($value)->save();
    }

    $form_state->setRedirectUrl($media_type->toUrl('collection'));
  }

}