You are here

function linkit_form_editor_link_dialog_alter in Linkit 8.5

Implements hook_form_FORM_ID_alter().

File

./linkit.module, line 51
Linkit hook implementations.

Code

function linkit_form_editor_link_dialog_alter(&$form, FormStateInterface $form_state, $form_id) {

  // Alter only the form with ID 'editor_link_dialog'.
  if ($form_id !== 'editor_link_dialog') {
    return;
  }

  /** @var Drupal\filter\Entity\FilterFormat $filter_format */
  $filter_format = $form_state
    ->getBuildInfo()['args'][0];

  /** @var \Drupal\Core\Entity\EntityStorageInterface $editorStorage */
  $editorStorage = Drupal::service('entity_type.manager')
    ->getStorage('editor');

  /** @var \Drupal\editor\EditorInterface $editor */
  $editor = $editorStorage
    ->load($filter_format
    ->id());
  $plugin_settings = $editor
    ->getSettings()['plugins']['drupallink'];

  // Do not alter the form if Linkit is not enabled for this text format.
  if (!isset($plugin_settings['linkit_enabled']) || isset($plugin_settings['linkit_enabled']) && !$plugin_settings['linkit_enabled']) {
    return;
  }
  $linkit_profile_id = $editor
    ->getSettings()['plugins']['drupallink']['linkit_profile'];
  if (isset($form_state
    ->getUserInput()['editor_object'])) {
    $input = $form_state
      ->getUserInput()['editor_object'];
    $form_state
      ->set('link_element', $input);
    $form_state
      ->setCached(TRUE);
  }
  else {

    // Retrieve the link element's attributes from form state.
    $input = $form_state
      ->get('link_element') ?: [];
  }
  $form['href_dirty_check'] = [
    '#type' => 'hidden',
    '#default_value' => isset($input['href']) ? $input['href'] : '',
  ];
  $form['attributes']['href'] = array_merge($form['attributes']['href'], [
    '#type' => 'linkit',
    '#description' => t('Start typing to find content.'),
    '#autocomplete_route_name' => 'linkit.autocomplete',
    '#autocomplete_route_parameters' => [
      'linkit_profile_id' => $linkit_profile_id,
    ],
    "#weight" => -10,
    '#default_value' => isset($input['href']) ? $input['href'] : '',
  ]);
  $fields = [
    'data-entity-type',
    'data-entity-uuid',
    'data-entity-substitution',
  ];
  $form['attributes']["#weight"] = -100;
  foreach ($fields as $field_name) {
    $form['attributes'][$field_name] = [
      '#title' => $field_name,
      '#type' => 'hidden',
      '#default_value' => isset($input[$field_name]) ? $input[$field_name] : '',
    ];
  }

  // Add #submit callback that handles the data-* attributes.
  array_unshift($form['#submit'], 'linkit_form_editor_link_dialog_submit');
}