You are here

function menu_target_edit_form_extra_elements in Menu target 8

Same name and namespace in other branches
  1. 7 menu_target.admin.inc \menu_target_edit_form_extra_elements()

Adds extra form elements to either node_form or menu_item_edit_form.

See also

menu_target_form_alter()

1 call to menu_target_edit_form_extra_elements()
menu_target_form_alter in ./menu_target.module
Implements hook_form_alter().

File

./menu_target.admin.inc, line 14
Allows content editors to choose wether or not to open menu items in a new window

Code

function menu_target_edit_form_extra_elements(&$form, $form_state, $node_form) {
  $config = Drupal::config('menu_target.settings');
  if ($node_form) {
    $type = $form_state['form_display']->bundle;
    $type_config = Drupal::config('menu.entity.node.' . $type);
    $enabled = $type_config
      ->get('available_menus');
    if (empty($enabled)) {
      return;
    }
  }

  // Only add extra form elements if the menu target functionality is enabled.
  if ($config
    ->get('enabled')) {

    // The achor (<a>) attribute is configurable in the menu configuration
    // form
    // (admin/structure/menu/settings).
    // If it is chosen to use valid XHTML, we will use class="target-blank" and
    // JavaScript will open the link in a
    // new window. If it us chosen to use a degradable workflow, we will
    // use target="_blank".
    $attribute = $config
      ->get('type') == 'html' ? 'target' : 'class';
    $attribute_value = $attribute == 'target' ? '_blank' : 'target-blank';

    // Get the currently stored menu options array.
    $options = $node_form ? $form['menu']['link']['options']['#value'] : $form['options']['#value'];

    // Create the form array.
    $target = array(
      '#type' => $attribute == 'html' ? 'select' : 'checkbox',
      '#title' => t('Open this link in a new window'),
      '#default_value' => isset($options['attributes']) && isset($options['attributes'][$attribute]) && in_array($attribute_value, $options['attributes'][$attribute]),
    );

    // Depanding on the form type, this element is placed in the
    // appropriate place in the form tree.
    if ($node_form) {
      $form['menu']['link']['target'] = $target;
    }
    else {

      // This is the menu item edit form.
      // Restructure the form in order to place the new target form element
      // just below the 'expanded' checkbox.
      $_form = $form;
      $form = array();
      foreach ($_form as $key => $element) {
        $form[$key] = $_form[$key];
        if ($key == 'expanded') {
          $form['target'] = $target;
        }
      }
    }

    // Add our own submit callback to the form.
    array_unshift($form['actions']['submit']['#submit'], 'menu_target_edit_form_extra_elements_submit');
  }
}