You are here

class MediaCombinedUploadForm in Media Directories 8

Same name and namespace in other branches
  1. 2.x modules/media_directories_ui/src/Form/MediaCombinedUploadForm.php \Drupal\media_directories_ui\Form\MediaCombinedUploadForm

A form to upload media of different bundles.

Hierarchy

Expanded class hierarchy of MediaCombinedUploadForm

1 file declares its use of MediaCombinedUploadForm
media_directories_ui.module in modules/media_directories_ui/media_directories_ui.module
Main module file.

File

modules/media_directories_ui/src/Form/MediaCombinedUploadForm.php, line 21

Namespace

Drupal\media_directories_ui\Form
View source
class MediaCombinedUploadForm extends FileUploadForm {

  /**
   * The file system service.
   *
   * @var \Drupal\Core\File\FileSystemInterface
   */
  protected $fileSystem;

  /**
   * The file system service.
   *
   * @var \Drupal\media_directories_ui\MediaDirectoriesUiHelper
   */
  protected $mediaDirectoriesUiHelper;

  /**
   * AddMediaFormBase constructor.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param \Drupal\Core\Session\AccountProxyInterface $current_user
   *   The current user.
   * @param \Drupal\Core\Utility\Token $token
   *   The token service.
   * @param \Drupal\Core\Theme\ThemeManagerInterface $theme_manager
   *   The theme manager.
   * @param \Drupal\Core\Render\ElementInfoManagerInterface $element_info
   *   The element info service.
   * @param \Drupal\Core\File\FileSystemInterface $file_system
   *   The file system.
   * @param \Drupal\media_directories_ui\MediaDirectoriesUiHelper $media_directories_ui_helper
   *   The media directories ui helper.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager, AccountProxyInterface $current_user, Token $token, ThemeManagerInterface $theme_manager, ElementInfoManagerInterface $element_info, FileSystemInterface $file_system, MediaDirectoriesUiHelper $media_directories_ui_helper) {
    parent::__construct($entity_type_manager, $current_user, $token, $theme_manager, $element_info);
    $this->fileSystem = $file_system;
    $this->mediaDirectoriesUiHelper = $media_directories_ui_helper;
  }

  /**
   * {@inheritDoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('entity_type.manager'), $container
      ->get('current_user'), $container
      ->get('token'), $container
      ->get('theme.manager'), $container
      ->get('element_info'), $container
      ->get('file_system'), $container
      ->get('media_directories_ui.helper'));
  }

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

  /**
   * {@inheritdoc}
   */
  public function buildInputElement(array $form, FormStateInterface $form_state) {
    $target_types = $this
      ->getTargetBundles($form_state);
    $validators_by_media_type = [];
    foreach ($target_types as $type) {
      $validators_by_media_type[$type] = $this
        ->getUploadValidators(MediaType::load($type));
    }
    $pre_render = (array) $this->elementInfo
      ->getInfoProperty('managed_file', '#pre_render', []);
    $form['container']['upload'] = [
      '#type' => 'managed_file',
      '#title' => $this
        ->t('Select files'),
      '#description' => $this
        ->t('Allowed file extensions: @extensions', [
        '@extensions' => $this->mediaDirectoriesUiHelper
          ->getValidExtensions($target_types),
      ]),
      '#multiple' => TRUE,
      // Upload to temporary folder. Needs to be moved into correct folder after saving.
      '#upload_location' => 'temporary://',
      '#upload_validators' => [
        'media_directories_ui_file_validator' => [
          $validators_by_media_type,
        ],
      ],
      '#process' => [
        [
          'Drupal\\file\\Element\\ManagedFile',
          'processManagedFile',
        ],
        '::processUploadElement',
      ],
      '#pre_render' => array_merge($pre_render, [
        [
          static::class,
          'preRenderUploadElement',
        ],
      ]),
    ];
    return $form;
  }

  /**
   * 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.
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   */
  protected function processInputValues(array $source_field_values, array $form, FormStateInterface $form_state) {
    $media = [];
    foreach ($source_field_values as $source_field_value) {
      $media_type = $this->mediaDirectoriesUiHelper
        ->getMediaType($source_field_value);
      $media_storage = $this->entityTypeManager
        ->getStorage('media');
      $source_field_name = $this
        ->getSourceFieldName($media_type);
      $field_config = $this->entityTypeManager
        ->getStorage('field_config')
        ->load('media.' . $media_type
        ->id() . '.' . $source_field_name);
      $destination = $this
        ->getUploadLocation($field_config
        ->getSettings());
      if ($this->fileSystem
        ->prepareDirectory($destination, FileSystemInterface::CREATE_DIRECTORY)) {
        $source_field_value = file_move($source_field_value, $destination);
      }
      $media[] = $this
        ->createMediaFromValue($media_type, $media_storage, $source_field_name, $source_field_value, $form_state);
    }

    // Re-key the media items before setting them in the form state.
    $form_state
      ->set('media', array_values($media));
    $form_state
      ->setRebuild();
  }

  /**
   * {@inheritdoc}
   */
  public function updateFormCallback(array &$form, FormStateInterface $form_state) {
    $triggering_element = $form_state
      ->getTriggeringElement();
    $wrapper_id = $triggering_element['#ajax']['wrapper'];
    $added_media = $form_state
      ->get('media');
    $response = new AjaxResponse();

    // 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;
    }

    // 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)) {
        $build = [
          '#theme' => 'media_directories_add',
          '#selected_type' => 'combined_upload',
          '#active_directory' => -1,
          '#target_bundles' => $this
            ->getTargetBundles($form_state),
          '#media_library_form_rebuild' => TRUE,
        ];
        $form_state
          ->setRebuild();
        $response
          ->addCommand(new ReplaceCommand('#media-library-add-form-wrapper', $build));
      }
      else {
        $response
          ->addCommand(new ReplaceCommand("#{$wrapper_id}", $form));
      }
    }
    else {
      $response
        ->addCommand(new ReplaceCommand("#{$wrapper_id}", $form));
    }
    return $response;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
AddMediaFormBase::$currentUser protected property Current user service.
AddMediaFormBase::$entityTypeManager protected property Entity type manager service.
AddMediaFormBase::$themeManager protected property The theme manager.
AddMediaFormBase::$token protected property The token replacement instance.
AddMediaFormBase::buildActions protected function Returns an array of supported actions for the form. 1
AddMediaFormBase::buildEntityFormElement protected function Builds the sub-form for setting required fields on a new media item. 1
AddMediaFormBase::buildForm public function Form constructor. Overrides FormInterface::buildForm 1
AddMediaFormBase::createFileItem protected function Create a file field item.
AddMediaFormBase::createMediaFromValue protected function Creates a new, unsaved media item from a source field value.
AddMediaFormBase::getCardinality protected function Get the current cardinality from the form state.
AddMediaFormBase::getDirectory protected function Gets the current active directory from the form state.
AddMediaFormBase::getMediaType protected function Get the media type from the form state. 2
AddMediaFormBase::getSelectionMode protected function Get the current selection mode from the form state.
AddMediaFormBase::getSourceFieldName protected function Returns the name of the source field for a media type. 1
AddMediaFormBase::getTargetBundles protected function Get the allowed target bundles from the form state. 1
AddMediaFormBase::getUploadLocation protected function Determines the URI for a file field.
AddMediaFormBase::getUploadValidators protected function Returns the upload validators for a field.
AddMediaFormBase::hideExtraSourceFieldComponents public static function Processes an image or file source field element.
AddMediaFormBase::removeButtonSubmit public function Submit handler for the remove button.
AddMediaFormBase::submitForm public function Form submission handler. Overrides FormInterface::submitForm 1
AddMediaFormBase::updateLibrary public function AJAX callback to send the new media item(s) to the media library.
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
FileUploadForm::$elementInfo protected property The element info discovery service.
FileUploadForm::prepareMediaEntityForSave protected function Makes the file of a media permanent.
FileUploadForm::preRenderUploadElement public static function Render API callback: Hides display of the proceed control.
FileUploadForm::processUploadElement public function Processes an upload (managed_file) element.
FileUploadForm::trustedCallbacks public static function Lists the trusted callbacks provided by the implementing class. Overrides TrustedCallbackInterface::trustedCallbacks
FileUploadForm::uploadButtonSubmit public function Submit handler for the upload button, inside the managed_file element.
FileUploadForm::validateUploadElement public function Validates the upload element.
FormBase::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 62
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MediaCombinedUploadForm::$fileSystem protected property The file system service.
MediaCombinedUploadForm::$mediaDirectoriesUiHelper protected property The file system service.
MediaCombinedUploadForm::buildInputElement public function Inheriting classes need to build the desired input element. Overrides FileUploadForm::buildInputElement
MediaCombinedUploadForm::create public static function Instantiates a new instance of this class. Overrides FileUploadForm::create
MediaCombinedUploadForm::getFormId public function Returns a unique string identifying the form. Overrides AddMediaFormBase::getFormId
MediaCombinedUploadForm::processInputValues protected function Creates media items from source field input values. Overrides AddMediaFormBase::processInputValues
MediaCombinedUploadForm::updateFormCallback public function AJAX callback to update the entire form based on source field input. Overrides AddMediaFormBase::updateFormCallback
MediaCombinedUploadForm::__construct public function AddMediaFormBase constructor. Overrides FileUploadForm::__construct
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
TrustedCallbackInterface::THROW_EXCEPTION constant Untrusted callbacks throw exceptions.
TrustedCallbackInterface::TRIGGER_SILENCED_DEPRECATION constant Untrusted callbacks trigger silenced E_USER_DEPRECATION errors.
TrustedCallbackInterface::TRIGGER_WARNING constant Untrusted callbacks trigger E_USER_WARNING errors.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.