You are here

function simple_megamenu_form_menu_link_content_form_alter in Simple Mega Menu 2.0.x

Same name and namespace in other branches
  1. 8 simple_megamenu.module \simple_megamenu_form_menu_link_content_form_alter()

Implements hook_form_BASE_FORM_ID_alter().

File

./simple_megamenu.module, line 111
Contains simple_megamenu.module.

Code

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

  /* @var \Drupal\menu_link_content\Entity\MenuLinkContent $menu_link */
  $menu_link = $form_state
    ->getFormObject()
    ->getEntity();
  $menu_name = $menu_link
    ->getMenuName();
  $menu_link_options = $menu_link->link
    ->first()->options ?: [];

  /* @var \Drupal\simple_megamenu\SimpleMegaMenuHelperInterface $simple_megamenu_helper */
  $simple_megamenu_helper = \Drupal::service('simple_megamenu.helper');
  $allowed_simple_mega_menu_types = $simple_megamenu_helper
    ->getMegaMenuTypeWhichTargetMenu($menu_name);
  $allowed_simple_mega_menu_types = array_keys($allowed_simple_mega_menu_types);
  if ($allowed_simple_mega_menu_types) {

    // The default value.
    $simple_mega_menu = NULL;

    // The default description for the entity reference form.
    $description = t('Select a simple mega menu entity to use on this menu link.');
    $simple_mega_menu_id = isset($menu_link_options['attributes']['data-simple-mega-menu']) ? $menu_link_options['attributes']['data-simple-mega-menu'] : NULL;
    if ($simple_mega_menu_id) {
      $simple_mega_menu = $simple_megamenu_helper
        ->getSimpleMegaMenu($simple_mega_menu_id);
      if ($simple_mega_menu instanceof SimpleMegaMenuInterface) {
        $destination = \Drupal::destination()
          ->getAsArray();
        $edit_path = Url::fromRoute('entity.simple_mega_menu.edit_form', [
          'simple_mega_menu' => $simple_mega_menu
            ->id(),
        ], [
          'query' => $destination,
        ])
          ->toString();
        $description = t('Select a simple mega menu entity to use on this menu link. Edit the entity referenced <a target="_blank" href="@edit_path">here</a>.', [
          '@edit_path' => $edit_path,
        ]);
      }
    }
    $form['simple_mega_menu'] = [
      '#title' => t('Simple Mega Menu'),
      '#description' => $description,
      '#weight' => $form['weight']['#weight'] + 1,
      '#type' => 'entity_autocomplete',
      '#default_value' => $simple_mega_menu,
      '#target_type' => 'simple_mega_menu',
      '#selection_handler' => 'default',
      '#selection_settings' => [
        'target_bundles' => $allowed_simple_mega_menu_types,
      ],
    ];
    $form['actions']['submit']['#submit'][] = 'simple_megamenu_menu_link_content_form_submit';
  }
}