You are here

class MediaEditForm in Media Directories 8

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

Class MediaEditForm.

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 MediaEditForm

1 file declares its use of MediaEditForm
MediaDirectoriesController.php in modules/media_directories_ui/src/Controller/MediaDirectoriesController.php

File

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

Namespace

Drupal\media_directories_ui\Form
View source
class MediaEditForm extends AddMediaFormBase {

  /**
   * Temporary store of the media entity.
   *
   * @var \Drupal\media\MediaInterface
   */
  public $media;

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

  /**
   * {@inheritdoc}
   */
  protected function getMediaType(FormStateInterface $form_state) {
    if (isset($this->media)) {
      return $this->entityTypeManager
        ->getStorage('media_type')
        ->load($this->media
        ->bundle());
    }
    return parent::getMediaType($form_state);
  }

  /**
   * {@inheritdoc}
   */
  protected function getTargetBundles(FormStateInterface $form_state) {
    $medias = $form_state
      ->get('media');
    if (is_array($medias)) {
      $bundles = [];
      foreach ($medias as $media) {
        $bundles[] = $media
          ->bundle();
      }
      return $bundles;
    }
    return parent::getTargetBundles($form_state);
  }

  /**
   * Form constructor.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   *
   * @return array
   *   The form structure.
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildForm($form, $form_state);

    // Add CSS for the left sided preview.
    $form['#attached']['library'][] = 'media_directories_ui/media-library.quick-edit-dialog';

    // Hide the creation message.
    $form['media']['description']['#access'] = FALSE;
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function buildInputElement(array $form, FormStateInterface $form_state) {

    // No need for an input element in the edit form.
  }

  /**
   * 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.
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   * @throws \Drupal\Core\Entity\EntityMalformedException
   */
  protected function buildEntityFormElement(MediaInterface $media, array $form, FormStateInterface $form_state, $delta) {

    // Set the media object to be used in overwritten methods.
    $this->media = $media;
    $element = parent::buildEntityFormElement($media, $form, $form_state, $delta);

    // Make the language field un-editable.
    if (isset($element['fields']['langcode'])) {
      $languages = $media
        ->getTranslationLanguages();
      $translations = [];
      foreach ($languages as $langcode => $language) {
        $translations[$langcode] = $media
          ->id();
      }

      // We allow altering the (source-)language, if no translation is made yet.
      if (count($translations) > 1) {
        $element['fields']['langcode']['#disabled'] = TRUE;
        $element['fields']['langcode']['#suffix'] = '<div>' . $this
          ->t('In this dialog you are only allowed to change the source language of medias having no translation yet.') . '</div>';
      }
    }

    // We show the left sided preview and provide a link to the full media edit page.
    if (!empty($element['preview'])) {
      $element['preview']['#access'] = TRUE;
      $link = new Link($this
        ->t('Edit in new tab'), $media
        ->toUrl('edit-form'));
      $element['preview']['edit_link'] = $link
        ->toRenderable();
      $element['preview']['edit_link']['#attributes']['class'][] = 'edit-link';
      $element['preview']['edit_link']['#attributes']['target'] = '_blank';
    }

    // Remove original button added by ManagedFile::processManagedFile().
    if (!empty($element['remove_button'])) {
      $element['remove_button']['#access'] = FALSE;
    }
    return $element;
  }

  /**
   * 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();
  }

  /**
   * 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) {
    return [
      '#type' => 'actions',
      'save' => [
        '#type' => 'submit',
        '#button_type' => 'primary',
        '#value' => $this
          ->t('Save'),
        '#ajax' => [
          'callback' => [
            get_called_class(),
            'saveMedia',
          ],
          'wrapper' => 'media-library-add-form-wrapper',
        ],
      ],
    ];
  }

  /**
   * Form submission handler.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   *
   * @return \Drupal\Core\Ajax\AjaxResponse
   *   An AJAX response.
   */
  public static function saveMedia(array &$form, FormStateInterface $form_state) {
    $response = new AjaxResponse();
    $added_media = $form_state
      ->get('media');
    foreach ($added_media as $delta => $media) {
      EntityFormDisplay::collectRenderDisplay($media, 'media_library')
        ->extractFormValues($media, $form['media'][$delta]['fields'], $form_state);

      // $this->prepareMediaEntityForSave($media);
      $media
        ->save();
    }
    $response
      ->addCommand(new LoadDirectoryContent());
    $response
      ->addCommand(new CloseModalDialogCommand());
    return $response;
  }

  /**
   * Form submission handler.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

    // Nothing to do here.
  }

}

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::create public static function Instantiates a new instance of this class. Overrides FormBase::create 2
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::getSelectionMode protected function Get the current selection mode from the form state.
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::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.
AddMediaFormBase::__construct public function AddMediaFormBase constructor. 2
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
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.
MediaEditForm::$media public property Temporary store of the media entity.
MediaEditForm::buildActions protected function Returns an array of supported actions for the form. Overrides AddMediaFormBase::buildActions
MediaEditForm::buildEntityFormElement protected function Builds the sub-form for setting required fields on a new media item. Overrides AddMediaFormBase::buildEntityFormElement
MediaEditForm::buildForm public function Form constructor. Overrides AddMediaFormBase::buildForm
MediaEditForm::buildInputElement public function Inheriting classes need to build the desired input element. Overrides AddMediaFormBase::buildInputElement
MediaEditForm::getFormId public function Returns a unique string identifying the form. Overrides AddMediaFormBase::getFormId
MediaEditForm::getMediaType protected function Get the media type from the form state. Overrides AddMediaFormBase::getMediaType
MediaEditForm::getSourceFieldName protected function Returns the name of the source field for a media type. Overrides AddMediaFormBase::getSourceFieldName
MediaEditForm::getTargetBundles protected function Get the allowed target bundles from the form state. Overrides AddMediaFormBase::getTargetBundles
MediaEditForm::saveMedia public static function Form submission handler.
MediaEditForm::submitForm public function Form submission handler. Overrides AddMediaFormBase::submitForm
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.
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.