You are here

class VideoEmbedDialog in Video Embed Field 8

Same name and namespace in other branches
  1. 8.2 modules/video_embed_wysiwyg/src/Form/VideoEmbedDialog.php \Drupal\video_embed_wysiwyg\Form\VideoEmbedDialog

A class for a video embed dialog.

Hierarchy

Expanded class hierarchy of VideoEmbedDialog

1 string reference to 'VideoEmbedDialog'
video_embed_wysiwyg.routing.yml in modules/video_embed_wysiwyg/video_embed_wysiwyg.routing.yml
modules/video_embed_wysiwyg/video_embed_wysiwyg.routing.yml

File

modules/video_embed_wysiwyg/src/Form/VideoEmbedDialog.php, line 25

Namespace

Drupal\video_embed_wysiwyg\Form
View source
class VideoEmbedDialog extends FormBase {

  /**
   * The video provider manager.
   *
   * @var \Drupal\video_embed_field\ProviderManager
   */
  protected $providerManager;

  /**
   * The renderer.
   *
   * @var \Drupal\Core\Render\RendererInterface
   */
  protected $renderer;

  /**
   * VideoEmbedDialog constructor.
   *
   * @param \Drupal\video_embed_field\ProviderManager $provider_manager
   *   The video provider plugin manager.
   * @param \Drupal\Core\Render\RendererInterface $renderer
   *   The renderer.
   */
  public function __construct(ProviderManager $provider_manager, RendererInterface $renderer) {
    $this->providerManager = $provider_manager;
    $this->render = $renderer;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('video_embed_field.provider_manager'), $container
      ->get('renderer'));
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, FilterFormat $filter_format = NULL) {

    // Add AJAX support.
    $form['#prefix'] = '<div id="video-embed-dialog-form">';
    $form['#suffix'] = '</div>';

    // Ensure relevant dialog libraries are attached.
    $form['#attached']['library'][] = 'editor/drupal.editor.dialog';

    // Simple URL field and submit button for video URL.
    $form['video_url'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Video URL'),
      '#required' => TRUE,
      '#default_value' => $this
        ->getUserInput($form_state, 'video_url'),
    ];

    // If no settings are found, use the defaults configured in the filter
    // formats interface.
    $settings = $this
      ->getUserInput($form_state, 'settings');
    if (empty($settings) && ($editor = Editor::load($filter_format
      ->id()))) {
      $editor_settings = $editor
        ->getSettings();
      $plugin_settings = NestedArray::getValue($editor_settings, [
        'plugins',
        'video_embed',
        'defaults',
        'children',
      ]);
      $settings = $plugin_settings ? $plugin_settings : [];
    }

    // Create a settings form from the existing video formatter.
    $form['settings'] = Video::mockInstance($settings)
      ->settingsForm([], new FormState());
    $form['settings']['#type'] = 'fieldset';
    $form['settings']['#title'] = $this
      ->t('Settings');
    $form['actions'] = [
      '#type' => 'actions',
    ];
    $form['actions']['save_modal'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Save'),
      '#submit' => [],
      '#ajax' => [
        'callback' => '::ajaxSubmit',
        'event' => 'click',
        'wrapper' => 'video-embed-dialog-form',
      ],
    ];
    return $form;
  }

  /**
   * Get a value from the widget in the WYSIWYG.
   *
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state to extract values from.
   * @param string $key
   *   The key to get from the selected WYSIWYG element.
   *
   * @return string
   *   The default value.
   */
  protected function getUserInput(FormStateInterface $form_state, $key) {
    return isset($form_state
      ->getUserInput()['editor_object'][$key]) ? $form_state
      ->getUserInput()['editor_object'][$key] : '';
  }

  /**
   * Get the values from the form and provider required for the client.
   *
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state from the dialog submission.
   * @param \Drupal\video_embed_field\ProviderPluginInterface $provider
   *   The provider loaded from the user input.
   *
   * @return array
   *   An array of values sent to the client for use in the WYSIWYG.
   */
  protected function getClientValues(FormStateInterface $form_state, ProviderPluginInterface $provider) {

    // All settings from the field formatter exist in the form and are relevant
    // for the rendering of the video.
    $video_formatter_settings = Video::defaultSettings();
    foreach ($video_formatter_settings as $key => $default) {
      $video_formatter_settings[$key] = $form_state
        ->getValue($key);
    }
    $provider
      ->downloadThumbnail();
    $thumbnail_preview = ImageStyle::load('video_embed_wysiwyg_preview')
      ->buildUrl($provider
      ->getLocalThumbnailUri());
    $thumbnail_preview_parts = parse_url($thumbnail_preview);
    return [
      'preview_thumbnail' => $thumbnail_preview_parts['path'] . (!empty($thumbnail_preview_parts['query']) ? '?' : '') . $thumbnail_preview_parts['query'],
      'video_url' => $form_state
        ->getValue('video_url'),
      'settings' => $video_formatter_settings,
      'settings_summary' => Video::mockInstance($video_formatter_settings)
        ->settingsSummary(),
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $provider = $this
      ->getProvider($form_state
      ->getValue('video_url'));

    // Display an error if no provider can be loaded for this video.
    if (FALSE == $provider) {
      $form_state
        ->setError($form['video_url'], $this
        ->t('Could not find a video provider to handle the given URL.'));
      return;
    }
  }

  /**
   * An AJAX submit callback to validate the WYSIWYG modal.
   */
  public function ajaxSubmit(array &$form, FormStateInterface $form_state) {
    $response = new AjaxResponse();
    if (!$form_state
      ->getErrors()) {

      // Load the provider and get the information needed for the client.
      $provider = $this
        ->getProvider($form_state
        ->getValue('video_url'));
      $response
        ->addCommand(new EditorDialogSave($this
        ->getClientValues($form_state, $provider)));
      $response
        ->addCommand(new CloseModalDialogCommand());
    }
    else {
      unset($form['#prefix'], $form['#suffix']);
      $form['status_messages'] = [
        '#type' => 'status_messages',
        '#weight' => -10,
      ];
      $response
        ->addCommand(new HtmlCommand(NULL, $form));
    }
    return $response;
  }

  /**
   * Get a provider from some input.
   *
   * @param string $input
   *   The input string.
   *
   * @return bool|\Drupal\video_embed_field\ProviderPluginInterface
   *   A video provider or FALSE on failure.
   */
  protected function getProvider($input) {
    return $this->providerManager
      ->loadProviderFromInput($input);
  }

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

    // The AJAX commands were already added in the AJAX callback. Do nothing in
    // the submit form.
  }

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

}

Members

Namesort descending Modifiers Type Description Overrides
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.
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.
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.
VideoEmbedDialog::$providerManager protected property The video provider manager.
VideoEmbedDialog::$renderer protected property The renderer.
VideoEmbedDialog::ajaxSubmit public function An AJAX submit callback to validate the WYSIWYG modal.
VideoEmbedDialog::buildForm public function Form constructor. Overrides FormInterface::buildForm
VideoEmbedDialog::create public static function Instantiates a new instance of this class. Overrides FormBase::create
VideoEmbedDialog::getClientValues protected function Get the values from the form and provider required for the client.
VideoEmbedDialog::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
VideoEmbedDialog::getProvider protected function Get a provider from some input.
VideoEmbedDialog::getUserInput protected function Get a value from the widget in the WYSIWYG.
VideoEmbedDialog::submitForm public function Form submission handler. Overrides FormInterface::submitForm
VideoEmbedDialog::validateForm public function Form validation handler. Overrides FormBase::validateForm
VideoEmbedDialog::__construct public function VideoEmbedDialog constructor.