You are here

class LinkitEditorDialog in Linkit 8.4

Provides a linkit dialog for text editors.

Hierarchy

Expanded class hierarchy of LinkitEditorDialog

1 string reference to 'LinkitEditorDialog'
linkit.routing.yml in ./linkit.routing.yml
linkit.routing.yml

File

src/Form/LinkitEditorDialog.php, line 24
Contains \Drupal\linkit\Form\LinkitEditorDialog.

Namespace

Drupal\linkit\Form
View source
class LinkitEditorDialog extends FormBase {

  /**
   * The editor storage service.
   *
   * @var \Drupal\Core\Entity\EntityStorageInterface
   */
  protected $editorStorage;

  /**
   * The linkit profile storage service.
   *
   * @var \Drupal\Core\Entity\EntityStorageInterface
   */
  protected $linkitProfileStorage;

  /**
   * The linkit profile.
   *
   * @var \Drupal\linkit\ProfileInterface
   */
  protected $linkitProfile;

  /**
   * Constructs a form object for linkit dialog.
   *
   * @param \Drupal\Core\Entity\EntityStorageInterface $editor_storage
   *   The editor storage service.
   * @param \Drupal\Core\Entity\EntityStorageInterface $linkit_profile_storage
   *   The linkit profile storage service.
   */
  public function __construct(EntityStorageInterface $editor_storage, EntityStorageInterface $linkit_profile_storage) {
    $this->editorStorage = $editor_storage;
    $this->linkitProfileStorage = $linkit_profile_storage;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('entity.manager')
      ->getStorage('editor'), $container
      ->get('entity.manager')
      ->getStorage('linkit_profile'));
  }

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

  /**
   * {@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) {

    // The default values are set directly from \Drupal::request()->request,
    // provided by the editor plugin opening the dialog.
    $user_input = $form_state
      ->getUserInput();
    $input = isset($user_input['editor_object']) ? $user_input['editor_object'] : [];

    /** @var \Drupal\editor\EditorInterface $editor */
    $editor = $this->editorStorage
      ->load($filter_format
      ->id());
    $linkit_profile_id = $editor
      ->getSettings()['plugins']['linkit']['linkit_profile'];
    $this->linkitProfile = $this->linkitProfileStorage
      ->load($linkit_profile_id);
    $form['#tree'] = TRUE;
    $form['#attached']['library'][] = 'editor/drupal.editor.dialog';
    $form['#prefix'] = '<div id="linkit-editor-dialog-form">';
    $form['#suffix'] = '</div>';

    // Everything under the "attributes" key is merged directly into the
    // generated link tag's attributes.
    $form['attributes']['href'] = [
      '#title' => $this
        ->t('Link'),
      '#type' => 'linkit',
      '#default_value' => isset($input['href']) ? $input['href'] : '',
      '#description' => $this
        ->t('Start typing to find content or paste a URL.'),
      '#autocomplete_route_name' => 'linkit.autocomplete',
      '#autocomplete_route_parameters' => [
        'linkit_profile_id' => $linkit_profile_id,
      ],
      '#weight' => 0,
    ];
    $this
      ->addAttributes($form, $form_state, $this->linkitProfile
      ->getAttributes(), $input);
    $form['actions'] = [
      '#type' => 'actions',
    ];
    $form['actions']['save_modal'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Save'),
      '#submit' => [],
      '#ajax' => [
        'callback' => '::submitForm',
        'event' => 'click',
      ],
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $attributes = array_filter($form_state
      ->getValue('attributes'));
    $form_state
      ->setValue('attributes', $attributes);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $response = new AjaxResponse();
    if ($form_state
      ->getErrors()) {
      unset($form['#prefix'], $form['#suffix']);
      $form['status_messages'] = [
        '#type' => 'status_messages',
        '#weight' => -10,
      ];
      $response
        ->addCommand(new HtmlCommand('#linkit-editor-dialog-form', $form));
    }
    else {
      $response
        ->addCommand(new EditorDialogSave($form_state
        ->getValues()));
      $response
        ->addCommand(new CloseModalDialogCommand());
    }
    return $response;
  }

  /**
   * Adds the attributes enabled on the current profile.
   *
   * @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.
   * @param AttributeCollection $attributes
   *   A collection of attributes for the current profile.
   * @param array $input
   *   An array with the attribute values from the editor.
   */
  private function addAttributes(array &$form, FormStateInterface &$form_state, AttributeCollection $attributes, array $input) {
    if ($attributes
      ->count()) {
      $form['linkit_attributes'] = [
        '#type' => 'container',
        '#title' => $this
          ->t('Attributes'),
        '#weight' => '10',
      ];

      /** @var \Drupal\linkit\AttributeInterface $plugin */
      foreach ($attributes as $plugin) {
        $plugin_name = $plugin
          ->getHtmlName();
        $default_value = isset($input[$plugin_name]) ? $input[$plugin_name] : '';
        $form['linkit_attributes'][$plugin_name] = $plugin
          ->buildFormElement($default_value);
        $form['linkit_attributes'][$plugin_name] += [
          '#parents' => [
            'attributes',
            $plugin_name,
          ],
        ];
      }
    }
  }

  /**
   * Gets the linkit profile entity.
   *
   * @return \Drupal\linkit\ProfileInterface
   *   The current linkit profile used by this form.
   */
  public function getLinkitProfile() {
    return $this->linkitProfile;
  }

}

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.
LinkitEditorDialog::$editorStorage protected property The editor storage service.
LinkitEditorDialog::$linkitProfile protected property The linkit profile.
LinkitEditorDialog::$linkitProfileStorage protected property The linkit profile storage service.
LinkitEditorDialog::addAttributes private function Adds the attributes enabled on the current profile.
LinkitEditorDialog::buildForm public function Overrides FormInterface::buildForm
LinkitEditorDialog::create public static function Instantiates a new instance of this class. Overrides FormBase::create
LinkitEditorDialog::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
LinkitEditorDialog::getLinkitProfile public function Gets the linkit profile entity.
LinkitEditorDialog::submitForm public function Form submission handler. Overrides FormInterface::submitForm
LinkitEditorDialog::validateForm public function Form validation handler. Overrides FormBase::validateForm
LinkitEditorDialog::__construct public function Constructs a form object for linkit dialog.
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.