You are here

abstract class AddMediaFormBase in Media Directories 3.x

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

Class AddMediaFormBase

Uses code and logic from core. We could try to integrate core directly, but it might be too unstable in this stage.

@package Drupal\media_directories_ui\Form

Hierarchy

Expanded class hierarchy of AddMediaFormBase

File

modules/media_directories_ui/src/Form/AddMediaFormBase.php, line 22

Namespace

Drupal\media_directories_ui\Form
View source
abstract class AddMediaFormBase extends AddFormBase {

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('entity_type.manager'), $container
      ->get('media_directories_ui.ui_builder'), $container
      ->get('media_library.opener_resolver'));
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'media_directories_add_form';
  }
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildForm($form, $form_state);
    $form['#action'] = Url::fromRoute('media_directories_library.ui', [], [
      'query' => $this
        ->getMediaLibraryState($form_state)
        ->all(),
    ])
      ->toString();
    $added_media = $this
      ->getAddedMediaItems($form_state);

    // Add back button to cancel uploading items.
    if (empty($added_media)) {
      $form['actions'] = [
        '#type' => 'actions',
        'back' => [
          '#type' => 'submit',
          '#value' => $this
            ->t('Back to the library'),
          '#ajax' => [
            'callback' => '::backToLibraryCallback',
            'wrapper' => 'media-library-wrapper',
          ],
        ],
      ];
    }
    return $form;
  }

  /**
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *
   * @return int|null
   */
  protected function getDirectory(FormStateInterface $form_state) {
    $state = $this
      ->getMediaLibraryState($form_state);
    $directory_id = (int) $state
      ->get('directory');
    if ($directory_id === MEDIA_DIRECTORY_ROOT) {
      $directory_id = NULL;
    }
    return $directory_id;
  }

  /**
   * 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) {
    $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)) {
        $form_state
          ->setRebuild();
        $response
          ->addCommand(new ReplaceCommand('#media-library-add-form-wrapper', $this
          ->buildMediaLibraryUi($form_state)));
        $response
          ->addCommand(new InvokeCommand('#media-library-add-form-wrapper :tabbable', 'focus'));
      }
      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'));
      }
    }
    else {
      $response
        ->addCommand(new ReplaceCommand("#{$wrapper_id}", $form));
      $response
        ->addCommand(new InvokeCommand('.media-library-add-form__added-media', 'focus'));
    }
    return $response;
  }

  /**
   * Go back to the library view.
   *
   * @param $form
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *
   * @return \Drupal\Core\Ajax\AjaxResponse
   */
  public function backToLibraryCallback(&$form, FormStateInterface $form_state) {
    $response = new AjaxResponse();
    $response
      ->addCommand(new ReplaceCommand('#media-library-wrapper', $this
      ->buildMediaLibraryUi($form_state)));
    $response
      ->addCommand(new InvokeCommand('#media-library-wrapper :tabbable', 'focus'));
    $form_state
      ->setRebuild();
    return $response;
  }
  protected function buildUploadUi(FormStateInterface $form_state) {

    // 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()
    $state = $this
      ->getMediaLibraryState($form_state);
    $state
      ->remove('media_library_content');

    //$state->set('_media_library_form_rebuild', TRUE);
    return $this->libraryUiBuilder
      ->buildUploadUi($state);
  }

  /**
   * 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, $form_state) {
      return $this
        ->createMediaFromValue($media_type, $media_storage, $source_field_name, $source_field_value, $form_state);
    }, $source_field_values);

    // Re-key the media items before setting them in the form state.
    $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();
  }

  /**
   * 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.
   *
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *
   * @return \Drupal\media\MediaInterface
   *   An unsaved media entity.
   */
  protected function createMediaFromValue(MediaTypeInterface $media_type, EntityStorageInterface $media_storage, $source_field_name, $source_field_value, FormStateInterface $form_state = NULL) {
    $media = $media_storage
      ->create([
      'bundle' => $media_type
        ->id(),
      $source_field_name => $source_field_value,
      'directory' => $this
        ->getDirectory($form_state),
    ]);
    $media
      ->setName($media
      ->getName());
    return $media;
  }
  protected function getMediaLibraryState(FormStateInterface $form_state) {
    $state = parent::getMediaLibraryState($form_state);
    $state
      ->remove('ajax_form');
    $state
      ->remove('_wrapper_format');
    return $state;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
AddFormBase::$entityTypeManager protected property The entity type manager.
AddFormBase::$libraryUiBuilder protected property The media library UI builder.
AddFormBase::$mediaType protected property The type of media items being created by this form.
AddFormBase::$openerResolver protected property The opener resolver.
AddFormBase::$viewBuilder protected property The media view builder.
AddFormBase::buildActions protected function Returns an array of supported actions for the form.
AddFormBase::buildCurrentSelectionArea protected function Returns a render array containing the current selection.
AddFormBase::buildEntityFormElement protected function Builds the sub-form for setting required fields on a new media item. 1
AddFormBase::buildInputElement abstract protected function Builds the element for submitting source field value(s). 3
AddFormBase::buildMediaLibraryUi protected function Build the render array of the media library UI.
AddFormBase::buildSelectedItemElement protected function Returns a render array for a single pre-selected media item.
AddFormBase::getAddedMediaItems protected function Get all added media items from the form state.
AddFormBase::getBaseFormId public function Returns a string identifying the base form. Overrides BaseFormIdInterface::getBaseFormId
AddFormBase::getCurrentMediaItems protected function Get all pre-selected and added media items from the form state.
AddFormBase::getMediaType protected function Get the media type from the form state. 2
AddFormBase::getPreSelectedMediaItems protected function Get all pre-selected media items from the form state.
AddFormBase::getSourceFieldName protected function Returns the name of the source field for a media type.
AddFormBase::isAdvancedUi protected function Determines if the "advanced UI" of the Media Library is enabled.
AddFormBase::prepareMediaEntityForSave protected function Prepares a created media item to be permanently saved. 1
AddFormBase::preRenderAddedMedia public function Converts the set of newly added media into an item list for rendering.
AddFormBase::removeButtonSubmit public function Submit handler for the remove button. 1
AddFormBase::submitForm public function Form submission handler. Overrides FormInterface::submitForm
AddFormBase::trustedCallbacks public static function Lists the trusted callbacks provided by the implementing class. Overrides TrustedCallbackInterface::trustedCallbacks
AddFormBase::updateLibrary public function AJAX callback to send the new media item(s) to the media library.
AddFormBase::updateWidget public function AJAX callback to send the new media item(s) to the calling code.
AddFormBase::validateForm public function Form validation handler. Overrides FormBase::validateForm
AddFormBase::validateMediaEntity protected function Validate a created media item.
AddFormBase::__construct public function Constructs an AddFormBase object. 2
AddMediaFormBase::backToLibraryCallback public function Go back to the library view.
AddMediaFormBase::buildForm public function Form constructor. Overrides AddFormBase::buildForm
AddMediaFormBase::buildUploadUi protected function
AddMediaFormBase::create public static function Instantiates a new instance of this class. Overrides AddFormBase::create 1
AddMediaFormBase::createMediaFromValue protected function Creates a new, unsaved media item from a source field value. Overrides AddFormBase::createMediaFromValue
AddMediaFormBase::getDirectory protected function
AddMediaFormBase::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
AddMediaFormBase::getMediaLibraryState protected function Get the media library state from the form state. Overrides AddFormBase::getMediaLibraryState
AddMediaFormBase::processInputValues protected function Creates media items from source field input values. Overrides AddFormBase::processInputValues
AddMediaFormBase::updateFormCallback public function AJAX callback to update the entire form based on source field input. Overrides AddFormBase::updateFormCallback
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 2
DependencySerializationTrait::__wakeup public function 2
FormBase::$configFactory protected property The config factory. 3
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. 3
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.
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.
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. 27
MessengerTrait::messenger public function Gets the messenger. 27
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. 4
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.