You are here

class FileUploadForm in Media Directories 8

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

A form to upload files.

Hierarchy

Expanded class hierarchy of FileUploadForm

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

File

modules/media_directories_ui/src/Form/FileUploadForm.php, line 20

Namespace

Drupal\media_directories_ui\Form
View source
class FileUploadForm extends AddMediaFormBase implements TrustedCallbackInterface {

  /**
   * The element info discovery service.
   *
   * @var \Drupal\Core\Render\ElementInfoManagerInterface
   */
  protected $elementInfo;

  /**
   * {@inheritDoc}
   */
  public static function trustedCallbacks() {
    return [
      'preRenderUploadElement',
    ];
  }

  /**
   * 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.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager, AccountProxyInterface $current_user, Token $token, ThemeManagerInterface $theme_manager, ElementInfoManagerInterface $element_info) {
    parent::__construct($entity_type_manager, $current_user, $token, $theme_manager);
    $this->elementInfo = $element_info;
  }

  /**
   * {@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'));
  }

  /**
   * {@inheritDoc}
   */
  protected function buildInputElement(array $form, FormStateInterface $form_state) {
    $media_type = $this
      ->getMediaType($form_state);
    $source_field = $media_type
      ->getSource()
      ->getConfiguration()['source_field'];
    $field_config = $this->entityTypeManager
      ->getStorage('field_config')
      ->load('media.' . $media_type
      ->id() . '.' . $source_field);
    $process = (array) $this->elementInfo
      ->getInfoProperty('managed_file', '#process', []);
    $pre_render = (array) $this->elementInfo
      ->getInfoProperty('managed_file', '#pre_render', []);
    $form['container']['upload'] = [
      '#type' => 'managed_file',
      '#title' => $field_config
        ->label(),
      '#description' => $this
        ->t('Allowed file extensions: @extensions', [
        '@extensions' => $field_config
          ->getSetting('file_extensions'),
      ]),
      '#upload_validators' => $this
        ->getUploadValidators($media_type),
      '#multiple' => TRUE,
      '#upload_location' => $this
        ->getUploadLocation($field_config
        ->getSettings()),
      '#process' => array_merge([
        '::validateUploadElement',
      ], $process, [
        '::processUploadElement',
      ]),
      '#pre_render' => array_merge($pre_render, [
        [
          static::class,
          'preRenderUploadElement',
        ],
      ]),
    ];
    return $form;
  }

  /**
   * Validates the upload element.
   *
   * @param array $element
   *   The upload element.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   *
   * @return array
   *   The processed upload element.
   */
  public function validateUploadElement(array $element, FormStateInterface $form_state) {

    /*    if ($form_state::hasAnyErrors()) {
        // When an error occurs during uploading files, remove all files so the
        // user can re-upload the files.
        $element['#value'] = [];
        }
        $values = $form_state->getValue('upload', []);
        if (count($values['fids']) > $element['#cardinality'] && $element['#cardinality'] !== FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED) {
        $form_state->setError($element, $this->t('A maximum of @count files can be uploaded.', [
        '@count' => $element['#cardinality'],
        ]));
        $form_state->setValue('upload', []);
        $element['#value'] = [];
        }*/
    return $element;
  }

  /**
   * Processes an upload (managed_file) element.
   *
   * @param array $element
   *   The upload element.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   *
   * @return array
   *   The processed upload element.
   */
  public function processUploadElement(array $element, FormStateInterface $form_state) {
    $element['upload_button']['#submit'] = [
      '::uploadButtonSubmit',
    ];

    /** @var \Drupal\media\MediaTypeInterface|string $media_type */
    $media_type = $form_state
      ->get('media_type');

    // Limit the validation errors to make sure
    // FormValidator::handleErrorsWithLimitedValidation doesn't remove the
    // current selection from the form state.
    // @see Drupal\Core\Form\FormValidator::handleErrorsWithLimitedValidation()
    $element['upload_button']['#limit_validation_errors'] = [
      [
        'upload',
      ],
      [
        'current_selection',
      ],
    ];
    $element['upload_button']['#ajax'] = [
      'callback' => '::updateFormCallback',
      'wrapper' => 'media-library-wrapper',
      // Add a fixed URL to post the form since AJAX forms are automatically
      // posted to <current> instead of $form['#action'].
      // @todo Remove when https://www.drupal.org/project/drupal/issues/2504115
      //   is fixed.
      'url' => Url::fromRoute('media_directories_ui.media.add'),
      'options' => [
        'query' => [
          'media_type' => is_object($media_type) ? $media_type
            ->id() : $media_type,
          'target_bundles' => $this
            ->getTargetBundles($form_state),
          'active_directory' => $this
            ->getDirectory($form_state),
          'cardinality' => $this
            ->getCardinality($form_state),
          'selection_mode' => $this
            ->getSelectionMode($form_state),
          FormBuilderInterface::AJAX_FORM_REQUEST => TRUE,
        ],
      ],
    ];

    // If a remove button is present, also allow to submit the from using a new button,
    // as the upload_button will be hidden with .hide-js by core.
    if (isset($element['remove_button'])) {
      $element['proceed_button'] = [
        '#type' => 'submit',
        '#value' => $this
          ->t('Proceed with all files from the list'),
      ];
      if (isset($element['upload_button']['#validate'])) {
        $element['proceed_button']['#validate'] = $element['upload_button']['#validate'];
      }
      if (isset($element['upload_button']['#submit'])) {
        $element['proceed_button']['#submit'] = $element['upload_button']['#submit'];
      }
      if (isset($element['upload_button']['#limit_validation_errors'])) {
        $element['proceed_button']['#limit_validation_errors'] = $element['upload_button']['#limit_validation_errors'];
      }
      if (isset($element['upload_button']['#ajax'])) {
        $element['proceed_button']['#ajax'] = $element['upload_button']['#ajax'];
      }
      if (isset($element['upload_button']['#weight'])) {
        $element['proceed_button']['#weight'] = $element['upload_button']['#weight'];
      }
    }
    return $element;
  }

  /**
   * Render API callback: Hides display of the proceed control.
   *
   * @see \Drupal\file\Element\ManagedFile::preRenderManagedFile()
   */
  public static function preRenderUploadElement($element) {
    if (isset($element['proceed_button'])) {

      // Make sure to be hidden, when the the remove button is hidden.
      if (isset($element['remove_button']['#access'])) {
        $element['proceed_button']['#access'] = $element['remove_button']['#access'];
      }
    }
    return $element;
  }

  /**
   * Submit handler for the upload button, inside the managed_file element.
   *
   * @param array $form
   *   The form render array.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   */
  public function uploadButtonSubmit(array $form, FormStateInterface $form_state) {
    $files = $this->entityTypeManager
      ->getStorage('file')
      ->loadMultiple($form_state
      ->getValue('upload', []));
    $this
      ->processInputValues($files, $form, $form_state);
  }

  /**
   * Makes the file of a media permanent.
   *
   * @param \Drupal\media\MediaInterface $media
   *   The media entity.
   *
   * @throws \Drupal\Core\Entity\EntityStorageException
   */
  protected function prepareMediaEntityForSave(MediaInterface $media) {

    /** @var \Drupal\file\FileInterface $file */
    $file = $media
      ->get($this
      ->getSourceFieldName($media->bundle->entity))->entity;
    $file
      ->setPermanent();
    $file
      ->save();
  }

}

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::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId 2
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::processInputValues protected function Creates media items from source field input values. 1
AddMediaFormBase::removeButtonSubmit public function Submit handler for the remove button.
AddMediaFormBase::submitForm public function Form submission handler. Overrides FormInterface::submitForm 1
AddMediaFormBase::updateFormCallback public function AJAX callback to update the entire form based on source field input. 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::buildInputElement protected function Inheriting classes need to build the desired input element. Overrides AddMediaFormBase::buildInputElement 1
FileUploadForm::create public static function Instantiates a new instance of this class. Overrides AddMediaFormBase::create 1
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.
FileUploadForm::__construct public function AddMediaFormBase constructor. Overrides AddMediaFormBase::__construct 1
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.
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.