You are here

class VideoFilterDialog in Video Filter 8

Provides Video Filter dialog for text editors.

Hierarchy

Expanded class hierarchy of VideoFilterDialog

1 string reference to 'VideoFilterDialog'
video_filter.routing.yml in ./video_filter.routing.yml
video_filter.routing.yml

File

src/Form/VideoFilterDialog.php, line 20

Namespace

Drupal\video_filter\Form
View source
class VideoFilterDialog extends FormBase implements ContainerInjectionInterface {

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('module_handler'));
  }

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

  /**
   * {@inheritdoc}
   *
   * @param \Drupal\filter\Entity\FilterFormat $filter_format
   *   The filter format for which this dialog corresponds.
   */
  public function buildForm(array $form, FormStateInterface $form_state, FilterFormat $filter_format = NULL) {
    $form['#tree'] = TRUE;
    $form['#attached']['library'][] = 'editor/drupal.editor.dialog';
    $form['#prefix'] = '<div id="video-filter-dialog-form">';
    $form['#suffix'] = '</div>';
    $form['url'] = [
      '#title' => $this
        ->t('Video URL'),
      '#type' => 'textfield',
      '#maxlength' => 2048,
      '#ajax' => [
        'callback' => '::getPluginOptions',
        'event' => 'change',
      ],
    ];
    $form['options'] = [];
    $vf = new VideoFilterCore();
    $plugins = $vf
      ->loadPlugins();
    foreach ($plugins['plugins'] as $id => $plugin_info) {
      if (!empty($plugin_info['options'])) {
        $form['options'][$id] = [
          '#type' => 'details',
          '#title' => $this
            ->t('Options'),
          '#open' => TRUE,
          '#prefix' => '<div class="visually-hidden">',
          '#suffix' => '</div>',
        ];
        $form['options'][$id]['options'] = $plugin_info['options'];
      }
    }
    $form['info']['empty'] = [
      '#markup' => $this
        ->t('Please copy URL from browser and paste it into Video URL field. Available embedding options will be displayed under this field.'),
      '#prefix' => '<div class="info-empty">',
      '#suffix' => '</div>',
    ];
    $form['info']['not-supported'] = [
      '#markup' => $this
        ->t('The URL you provided is not supported. Please contact your developer to extend this module.'),
      '#prefix' => '<div class="visually-hidden">',
      '#suffix' => '</div>',
    ];
    $form['align'] = [
      '#title' => $this
        ->t('Align (optional)'),
      '#type' => 'select',
      '#default_value' => 'none',
      '#options' => [
        'none' => $this
          ->t('None'),
        'left' => $this
          ->t('Left'),
        'right' => $this
          ->t('Right'),
        'center' => $this
          ->t('Center'),
      ],
      '#prefix' => '<div class="visually-hidden">',
      '#suffix' => '</div>',
    ];
    $form['actions'] = [
      '#type' => 'actions',
    ];
    $form['actions']['save_modal'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Insert'),
      // No regular submit-handler. This form only works via JavaScript.
      '#submit' => [],
      '#ajax' => [
        'callback' => '::submitForm',
        'event' => 'click',
      ],
      '#attributes' => [
        'disabled' => 'true',
      ],
    ];

    // This is the element where we put generated code
    // By doing this we can generate [video:url]
    // in PHP instead of generating it in CKEditor JS plugin.
    $form['attributes']['code'] = [
      '#title' => $this
        ->t('Video Filter'),
      '#type' => 'textfield',
      '#prefix' => '<div class="visually-hidden">',
      '#suffix' => '</div>',
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $response = new AjaxResponse();

    // Generate shortcut/token code.
    $url = $form_state
      ->getValue('url');
    $supported = FALSE;

    // Check URL and validate is provider is supported.
    // If yes then generate a token with all the parameters from a dialog form.
    if ($url) {
      $shortcode = '[video:' . $url;
      $input = $form_state
        ->getUserInput();
      $vf = new VideoFilterCore();
      $plugin = $vf
        ->loadPlugins($url);
      if (!empty($plugin['options'])) {
        foreach ($input['options'][$plugin['id']]['options'] as $key => $val) {
          if (!empty($val)) {
            $shortcode .= ' ' . $key . ':' . $val;
          }
        }
        $shortcode .= ' provider:' . $plugin['id'];
        $supported = TRUE;
      }
      if ($form_state
        ->getValue('align') && $form_state
        ->getValue('align') != 'none') {
        $shortcode .= ' align:' . $form_state
          ->getValue('align');
      }
      $shortcode .= ']';
    }
    if ($supported && !empty($url)) {
      $form_state
        ->setValue([
        'attributes',
        'code',
      ], $shortcode);
    }
    if ($form_state
      ->getErrors()) {
      unset($form['#prefix'], $form['#suffix']);
      $form['status_messages'] = [
        '#type' => 'status_messages',
        '#weight' => -10,
      ];
      $response
        ->addCommand(new HtmlCommand('#video-filter-dialog-form', $form));
    }
    else {
      $response
        ->addCommand(new EditorDialogSave($form_state
        ->getValues()));
      $response
        ->addCommand(new CloseModalDialogCommand());
    }
    return $response;
  }

  /**
   * Get plugin embedding options.
   */
  public function getPluginOptions(array &$form, FormStateInterface $form_state) {
    $response = new AjaxResponse();

    // Video URL.
    $url = $form_state
      ->getValue('url');
    if (!empty($url)) {
      $vf = new VideoFilterCore();
      $plugin = $vf
        ->loadPlugins($url);
      if (!empty($plugin['id'])) {

        // Show embedding options.
        $form['options'][$plugin['id']]['#prefix'] = '';
        $form['options'][$plugin['id']]['#suffix'] = '';

        // Enable button.
        $form['actions']['save_modal']['#attributes'] = [];

        // Enalbe algin options.
        $form['align']['#prefix'] = '';
        $form['align']['#suffix'] = '';

        // Hide Instructions message.
        $form['info']['empty']['#prefix'] = '<div class="visually-hidden">';
        $form['info']['empty']['#suffix'] = '</div>';

        // Hide Not Supported message.
        $form['info']['not-supported']['#prefix'] = '<div class="visually-hidden">';
        $form['info']['not-supported']['#suffix'] = '</div>';
      }
      else {

        // Hide Insert button.
        $form['actions']['save_modal']['#attributes'] = [
          'disabled' => 'true',
        ];

        // Hide Instructions message.
        $form['info']['empty']['#prefix'] = '<div class="visually-hidden">';
        $form['info']['empty']['#suffix'] = '</div>';

        // Show Not Supported message.
        $form['info']['not-supported']['#prefix'] = '';
        $form['info']['not-supported']['#suffix'] = '';
      }
    }
    $response
      ->addCommand(new HtmlCommand('#video-filter-dialog-form', $form));
    return $response;
  }

}

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.
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.
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.
VideoFilterDialog::buildForm public function Overrides FormInterface::buildForm
VideoFilterDialog::create public static function Instantiates a new instance of this class. Overrides FormBase::create
VideoFilterDialog::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
VideoFilterDialog::getPluginOptions public function Get plugin embedding options.
VideoFilterDialog::submitForm public function Form submission handler. Overrides FormInterface::submitForm