You are here

function menu_link_weight_node_form_submit in Menu Link Weight 8

Same name and namespace in other branches
  1. 8.2 menu_link_weight.node.inc \menu_link_weight_node_form_submit()
  2. 7 menu_link_weight.module \menu_link_weight_node_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).

1 string reference to 'menu_link_weight_node_form_submit'
menu_link_weight_form_node_form_alter in ./menu_link_weight.node.inc
Implements hook_form_BASE_FORM_ID_alter() for node forms.

File

./menu_link_weight.node.inc, line 250

Code

function menu_link_weight_node_form_submit($form, FormStateInterface $form_state) {

  // Return on empty submissions or if menu selection not enabled.
  if (!$form_state
    ->hasValue([
    'menu',
    'menu_link_weight',
  ]) || !$form_state
    ->getValue([
    'menu',
    'enabled',
  ])) {
    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);
  }
}