You are here

class CKEditorEntityLinkDialog in CKEditor Entity Link 8

Provides a link dialog for text editors.

Hierarchy

Expanded class hierarchy of CKEditorEntityLinkDialog

1 string reference to 'CKEditorEntityLinkDialog'
ckeditor_entity_link.routing.yml in ./ckeditor_entity_link.routing.yml
ckeditor_entity_link.routing.yml

File

src/Form/CKEditorEntityLinkDialog.php, line 22

Namespace

Drupal\ckeditor_entity_link\Form
View source
class CKEditorEntityLinkDialog extends FormBase implements BaseFormIdInterface {

  /**
   * Entity type manager service.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * Class constructor.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   Entity type manager service.
   */

  /**
   * The entity repository.
   *
   * @var \Drupal\Core\Entity\EntityRepositoryInterface
   */
  protected $entityRepository;

  /**
   * CKEditorEntityLinkDialog constructor.
   *
   * @param \Drupal\Core\Entity\EntityRepositoryInterface $entity_repository
   *   Entity repository.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager, EntityRepositoryInterface $entity_repository) {
    $this->entityTypeManager = $entity_type_manager;
    $this->entityRepository = $entity_repository;
  }

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

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

  /**
   * {@inheritdoc}
   */
  public function getBaseFormId() {

    // Use the EditorLinkDialog form id to ease alteration.
    return 'editor_link_dialog';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, FilterFormat $filter_format = NULL) {
    $config = $this
      ->config('ckeditor_entity_link.settings');

    // The default values are set directly from \Drupal::request()->request,
    // provided by the editor plugin opening the dialog.
    $form['#tree'] = TRUE;
    $form['#attached']['library'][] = 'editor/drupal.editor.dialog';
    $form['#prefix'] = '<div id="ckeditor-entity-link-dialog-form">';
    $form['#suffix'] = '</div>';
    $entity_types = $this->entityTypeManager
      ->getDefinitions();
    $types = [];
    foreach ($config
      ->get('entity_types') as $type => $selected) {
      if ($selected) {
        $types[$type] = $entity_types[$type]
          ->getLabel();
      }
    }
    $form['entity_type'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Link type'),
      '#options' => $types,
      '#default_value' => 'node',
      '#required' => TRUE,
      '#size' => 1,
      '#ajax' => [
        'callback' => '::updateTypeSettings',
        'effect' => 'fade',
      ],
    ];
    $entity_type = empty($form_state
      ->getValue('entity_type')) ? 'node' : $form_state
      ->getValue('entity_type');
    $bundles = [];
    foreach ($config
      ->get($entity_type . '_bundles') as $bundle => $selected) {
      if ($selected) {
        $bundles[] = $bundle;
      }
    }
    $form['entity_id'] = [
      '#type' => 'entity_autocomplete',
      '#target_type' => $entity_type,
      '#title' => $this
        ->t('Link'),
      '#required' => TRUE,
      '#prefix' => '<div id="entity-id-wrapper">',
      '#suffix' => '</div>',
    ];
    if (!empty($bundles)) {
      $form['entity_id']['#selection_settings']['target_bundles'] = $bundles;
    }
    $form['actions'] = [
      '#type' => 'actions',
    ];
    $form['actions']['save_modal'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Save'),
      // No regular submit-handler. This form only works via JavaScript.
      '#submit' => [],
      '#ajax' => [
        'callback' => '::submitForm',
        'event' => 'click',
      ],
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   *
   * @return \Drupal\Core\Ajax\AjaxResponse
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   * @throws \Drupal\Core\Entity\EntityMalformedException
   */
  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('#ckeditor-entity-link-dialog-form', $form));
    }
    else {
      $entity = $this->entityTypeManager
        ->getStorage($form_state
        ->getValue('entity_type'))
        ->load($form_state
        ->getValue('entity_id'));

      // Get the entity translation from context.
      $entity = $this->entityRepository
        ->getTranslationFromContext($entity);
      $values = [
        'attributes' => [
          'href' => $this
            ->getUrl($entity),
        ] + $form_state
          ->getValue('attributes', []),
      ];
      $response
        ->addCommand(new EditorDialogSave($values));
      $response
        ->addCommand(new CloseModalDialogCommand());
    }
    return $response;
  }

  /**
   * Helper function to return entity url.
   *
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   Entity.
   *
   * @return string
   *   Entity url.
   * @throws \Drupal\Core\Entity\EntityMalformedException
   */
  public function getUrl(EntityInterface $entity) {
    switch ($entity
      ->getEntityType()
      ->get('id')) {
      case 'menu_link_content':
        return $entity
          ->getUrlObject()
          ->toString();
      case 'shortcut':
        return $entity
          ->getUrl()
          ->toString();
      case 'file':

        // Method toUrl is not implemented for File Entity, use File::url() instead.
        // Do not confuse with deprecated EntityInterface::url().
        return $entity
          ->url();
      default:
        return $entity
          ->toUrl()
          ->toString();
    }
  }

  /**
   * Ajax callback to update the form fields which depend on embed type.
   *
   * @param array $form
   *   The build form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   *
   * @return \Drupal\Core\Ajax\AjaxResponse
   *   Ajax response with updated options for the embed type.
   */
  public function updateTypeSettings(array &$form, FormStateInterface $form_state) {
    $response = new AjaxResponse();

    // Update options for entity type bundles.
    $response
      ->addCommand(new ReplaceCommand('#entity-id-wrapper', $form['entity_id']));
    return $response;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
CKEditorEntityLinkDialog::$entityRepository protected property The entity repository.
CKEditorEntityLinkDialog::$entityTypeManager protected property Entity type manager service.
CKEditorEntityLinkDialog::buildForm public function Form constructor. Overrides FormInterface::buildForm
CKEditorEntityLinkDialog::create public static function Instantiates a new instance of this class. Overrides FormBase::create
CKEditorEntityLinkDialog::getBaseFormId public function Returns a string identifying the base form. Overrides BaseFormIdInterface::getBaseFormId
CKEditorEntityLinkDialog::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
CKEditorEntityLinkDialog::getUrl public function Helper function to return entity url.
CKEditorEntityLinkDialog::submitForm public function Overrides FormInterface::submitForm
CKEditorEntityLinkDialog::updateTypeSettings public function Ajax callback to update the form fields which depend on embed type.
CKEditorEntityLinkDialog::__construct public function CKEditorEntityLinkDialog constructor.
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.