You are here

function menu_link_weight_menu_link_content_form_submit in Menu Link Weight 8

Same name and namespace in other branches
  1. 8.2 menu_link_weight.menu_ui.inc \menu_link_weight_menu_link_content_form_submit()

Custom submit hook for node form which reorders menu link weights.

Note: this wil not reorder links that the current user does not have access to (ie. links to access-controlled nodes).

2 string references to 'menu_link_weight_menu_link_content_form_submit'
menu_link_weight_form_menu_link_content_form_alter in ./menu_link_weight.menu_ui.inc
Implements hook_form_BASE_FORM_ID_alter() for menu_link_content edit forms.
menu_link_weight_form_menu_link_edit_alter in ./menu_link_weight.menu_ui.inc
Implements hook_form_BASE_FORM_ID_alter() for menu link edit forms.

File

./menu_link_weight.menu_ui.inc, line 283

Code

function menu_link_weight_menu_link_content_form_submit($form, FormStateInterface $form_state) {

  // Return on empty submissions or if menu selection not enabled.
  if (!$form_state
    ->hasValue([
    'menu',
    'menu_link_weight',
  ])) {
    return;
  }

  /** @var \Drupal\Core\Menu\MenuLinkManagerInterface $menu_link_manager */
  $menu_link_manager = \Drupal::service('plugin.manager.menu.link');
  $connection = \Drupal::database();
  $transaction = $connection
    ->startTransaction();
  try {

    // Because the form elements were keyed with the item ids from the database,
    // we can simply iterate through the submitted values.
    foreach ($form_state
      ->getValue([
      'menu',
      'menu_link_weight',
    ]) as $link_id => $info) {
      if ($link_id == 'link_current') {

        // Do nothing. Changing the weight of the current link will be handled
        // by menu_ui_form_node_form_submit() instead.
        continue;
      }

      /** @var \Drupal\Core\Menu\MenuLinkInterface $link */
      $menu_link_manager
        ->updateDefinition($link_id, [
        'weight' => $info['weight'],
      ]);
    }
  } catch (Exception $e) {
    $transaction
      ->rollback();
    watchdog_exception('menu_link_weight', $e);
  }
}