Commit 3a3cbaae authored by Liam Morland's avatar Liam Morland Committed by Lily Yan
Browse files

ISTWCMS-4082: Allow creating disabled menu items on node edit pages

parent c6a0a16c
......@@ -6,6 +6,7 @@
*/
use Drupal\Core\Form\FormStateInterface;
use Drupal\menu_link_content\Entity\MenuLinkContent;
/**
* Implements hook_form_BASE_FORM_ID_alter().
......@@ -13,6 +14,40 @@ use Drupal\Core\Form\FormStateInterface;
function uw_sites_all_form_node_form_alter(array &$form, FormStateInterface $form_state, string $form_id): void {
// Add submit handler.
$form['actions']['submit']['#submit'][] = '_uw_sites_all_form_node_form_submit';
// Allow a page to have a menu link with the 'enabled' property false.
if (isset($form['menu']['link'])) {
// Rename "Provide a menu link".
$form['menu']['enabled']['#title'] = t('Place in site hierarchy');
// Get current value for the 'enabled' property, defaulting to TRUE.
$enabled = TRUE;
if (!empty($form['menu']['link']['entity_id']['#value'])) {
$entity_id = (int) $form['menu']['link']['entity_id']['#value'];
$menu_link = MenuLinkContent::load($entity_id);
if (isset($menu_link)) {
$enabled = $menu_link->isEnabled();
}
}
// Create checkbox for hiding menu links.
$form['menu']['link']['place_in_menu'] = [
'#type' => 'checkbox',
'#title' => t('Add menu link'),
'#weight' => -50,
'#default_value' => $enabled,
];
// Hide menu fields that do not apply when the menu link is not enabled.
$hide_state = [
'invisible' => [
'input[name="menu[place_in_menu]"]' => ['checked' => FALSE],
],
];
$form['menu']['link']['title']['#states'] = $hide_state;
$form['menu']['link']['description']['#states'] = $hide_state;
$form['menu']['link']['weight']['#states'] = $hide_state;
}
}
/**
......@@ -27,6 +62,22 @@ function _uw_sites_all_form_node_form_submit(array $form, FormStateInterface &$f
if ($nid && substr($form_id, -10) !== '_edit_form' && isset($fieldDefinitions['layout_builder__layout'])) {
$form_state->setRedirect('layout_builder.overrides.node.view', ['node' => $nid]);
}
// If a page is in the site hierarchy, enable or disabled its menu item based
// on place_in_menu selection.
$in_hierarchy = $form_state->getValue(['menu', 'enabled']);
if ($in_hierarchy) {
$entity_id = (int) $form_state->getValue(['menu', 'entity_id']);
$enabled = (bool) $form_state->getValue(['menu', 'place_in_menu']);
$menu_link = MenuLinkContent::load($entity_id);
// If JS is disabled, "Menu link title" will not be automatically filled. If
// the title is empty, no link will be created and the following will error.
// So, only run these if the menu link exists.
if ($menu_link) {
$menu_link->set('enabled', $enabled);
$menu_link->save();
}
}
}
/**
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment