Same name and namespace in other branches
  1. 8.9.x core/modules/menu_ui/menu_ui.module \menu_ui_form_node_type_form_alter()
  2. 9 core/modules/menu_ui/menu_ui.module \menu_ui_form_node_type_form_alter()

Implements hook_form_FORM_ID_alter() for \Drupal\node\NodeTypeForm.

Adds menu options to the node type form.

See also

NodeTypeForm::form()

menu_ui_form_node_type_form_builder()

File

core/modules/menu_ui/menu_ui.module, line 360
Allows administrators to customize the site's navigation menus.

Code

function menu_ui_form_node_type_form_alter(&$form, FormStateInterface $form_state) {

  /** @var \Drupal\Core\Menu\MenuParentFormSelectorInterface $menu_parent_selector */
  $menu_parent_selector = \Drupal::service('menu.parent_form_selector');
  $menu_options = array_map(function (MenuInterface $menu) {
    return $menu
      ->label();
  }, Menu::loadMultiple());
  asort($menu_options);

  /** @var \Drupal\node\NodeTypeInterface $type */
  $type = $form_state
    ->getFormObject()
    ->getEntity();
  $form['menu'] = [
    '#type' => 'details',
    '#title' => t('Menu settings'),
    '#attached' => [
      'library' => [
        'menu_ui/drupal.menu_ui.admin',
      ],
    ],
    '#group' => 'additional_settings',
  ];
  $form['menu']['menu_options'] = [
    '#type' => 'checkboxes',
    '#title' => t('Available menus'),
    '#default_value' => $type
      ->getThirdPartySetting('menu_ui', 'available_menus', [
      'main',
    ]),
    '#options' => $menu_options,
    '#description' => t('Content of this type can be placed in the selected menus.'),
  ];

  // @todo See if we can avoid pre-loading all options by changing the form or
  //   using a #process callback. https://www.drupal.org/node/2310319
  //   To avoid an 'illegal option' error after saving the form we have to load
  //   all available menu parents. Otherwise, it is not possible to dynamically
  //   add options to the list using ajax.
  $options_cacheability = new CacheableMetadata();
  $options = $menu_parent_selector
    ->getParentSelectOptions('', NULL, $options_cacheability);
  $form['menu']['menu_parent'] = [
    '#type' => 'select',
    '#title' => t('Default parent link'),
    '#default_value' => $type
      ->getThirdPartySetting('menu_ui', 'parent', 'main:'),
    '#options' => $options,
    '#description' => t('Choose the menu link to be the default parent for a new link in the content authoring form.'),
    '#attributes' => [
      'class' => [
        'menu-title-select',
      ],
    ],
  ];
  $options_cacheability
    ->applyTo($form['menu']['menu_parent']);
  $form['#validate'][] = 'menu_ui_form_node_type_form_validate';
  $form['#entity_builders'][] = 'menu_ui_form_node_type_form_builder';
}