You are here

class SoundcloudForm in Media entity Soundcloud 3.x

Same name and namespace in other branches
  1. 8.2 src/Form/SoundcloudForm.php \Drupal\media_entity_soundcloud\Form\SoundcloudForm

Hierarchy

Expanded class hierarchy of SoundcloudForm

File

src/Form/SoundcloudForm.php, line 17

Namespace

Drupal\media_entity_soundcloud\Form
View source
class SoundcloudForm extends AddFormBase {

  /**
   * The http client.
   *
   * @var \GuzzleHttp\ClientInterface
   */
  protected $httpClient;

  /**
   * Constructs a AddFormBase object.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param \Drupal\media_library\MediaLibraryUiBuilder $library_ui_builder
   *   The media library UI builder.
   * @param \Drupal\media_library\OpenerResolverInterface $opener_resolver
   *   The opener resolver.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager, MediaLibraryUiBuilder $library_ui_builder, ClientInterface $http_client, OpenerResolverInterface $opener_resolver = NULL) {
    parent::__construct($entity_type_manager, $library_ui_builder, $opener_resolver);
    $this->httpClient = $http_client;
  }

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

  /**
   * {@inheritdoc}
   */
  protected function getMediaType(FormStateInterface $form_state) {
    if ($this->mediaType) {
      return $this->mediaType;
    }
    $media_type = parent::getMediaType($form_state);
    if (!$media_type
      ->getSource() instanceof Soundcloud) {
      throw new \InvalidArgumentException('Can only add media types which use an Soundcloud source plugin.');
    }
    return $media_type;
  }

  /**
   * {@inheritDoc}
   */
  protected function buildInputElement(array $form, \Drupal\Core\Form\FormStateInterface $form_state) {
    $container = [
      '#type' => 'container',
    ];
    $container['soundcloud_url'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t("Add Soundcloud Track"),
    ];
    $container['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Add'),
      '#button_type' => 'primary',
      '#submit' => [
        '::addButtonSubmit',
      ],
      '#validate' => [
        '::validateSoundcloudUrl',
      ],
      '#ajax' => [
        'callback' => '::updateFormCallback',
        'wrapper' => 'media-library-wrapper',
        // @todo Remove when https://www.drupal.org/project/drupal/issues/2504115
        //   is fixed.
        'url' => Url::fromRoute('media_library.ui'),
        'options' => [
          'query' => $this
            ->getMediaLibraryState($form_state)
            ->all() + [
            FormBuilderInterface::AJAX_FORM_REQUEST => TRUE,
          ],
        ],
      ],
    ];
    $form['container'] = $container;
    return $form;
  }

  /**
   * Validates a soundcloud url.
   *
   * @param array $form
   *    The form.
   * @param FormStateInterface $form_state
   *    The form state.
   *
   * @return void|TRUE
   */
  public function validateSoundcloudUrl(array &$form, FormStateInterface $form_state) {
    $url = $form_state
      ->getValue('soundcloud_url');
    if (preg_match('/https?:\\/\\/(www\\.)?soundcloud\\.com\\/.*/', $url)) {
      try {
        \Drupal::httpClient()
          ->get($url);
      } catch (ClientException $e) {
        $form_state
          ->setErrorByName('url', $this
          ->t('Could not connect to the track, please make sure that the url is correct.'));
      }
    }
    else {
      $form_state
        ->setErrorByName('url', $this
        ->t('Invalid url.'));
    }
  }

  /**
   * {@inheritDoc}
   */
  public function addButtonSubmit(array $form, \Drupal\Core\Form\FormStateInterface $form_state) {
    $this
      ->processInputValues([
      $form_state
        ->getValue('soundcloud_url'),
    ], $form, $form_state);
  }

  /**
   * {@inheritDoc}
   */
  function getFormId() {
    return 'soundcloud_media_add_form';
  }

}

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::buildForm public function Form constructor. Overrides FormInterface::buildForm
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::createMediaFromValue protected function Creates a new, unsaved media item from a source field value. 1
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::getMediaLibraryState protected function Get the media library state from the form state.
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::processInputValues protected function Creates media items from source field input values.
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::updateFormCallback public function AJAX callback to update the entire form based on source field input.
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.
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.
SoundcloudForm::$httpClient protected property The http client.
SoundcloudForm::addButtonSubmit public function
SoundcloudForm::buildInputElement protected function Builds the element for submitting source field value(s). Overrides AddFormBase::buildInputElement
SoundcloudForm::create public static function Instantiates a new instance of this class. Overrides AddFormBase::create
SoundcloudForm::getFormId function Returns a unique string identifying the form. Overrides FormInterface::getFormId
SoundcloudForm::getMediaType protected function Get the media type from the form state. Overrides AddFormBase::getMediaType
SoundcloudForm::validateSoundcloudUrl public function Validates a soundcloud url.
SoundcloudForm::__construct public function Constructs a AddFormBase object. Overrides AddFormBase::__construct
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.