function menu_link_weight_node_form_validate in Menu Link Weight 8
Same name and namespace in other branches
- 8.2 menu_link_weight.node.inc \menu_link_weight_node_form_validate()
- 7 menu_link_weight.module \menu_link_weight_node_form_validate()
Validation hook for the menu_link weight element.
1 string reference to 'menu_link_weight_node_form_validate'
- 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 203
Code
function menu_link_weight_node_form_validate($form, FormStateInterface $form_state) {
/** @var \Drupal\Core\Menu\MenuLinkManagerInterface $menu_link_manager */
$menu_link_manager = \Drupal::service('plugin.manager.menu.link');
$parent_element = $form['menu']['link']['menu_parent'];
$parent_value = _menu_link_weight_get_parent_value_from_element($parent_element, $form_state);
if ($form_state
->hasValue([
'menu',
'menu_link_weight',
])) {
list($menu_name, $parent_id) = explode(':', $parent_value, 2);
// Loop through submitted weights and confirm that the parent link/menu
// are still the same.
$weights = $form_state
->getValue([
'menu',
'menu_link_weight',
]);
unset($weights['link_current']);
foreach ($weights as $link_id => $weight) {
/** @var \Drupal\Core\Menu\MenuLinkInterface $link */
$link = $menu_link_manager
->createInstance($link_id);
if ($link
->getParent() != $parent_id) {
$form_state
->setErrorByName('menu][menu_link_weight', t('The parent for one of the menu links have been changed by another user, please try again.'));
}
if ($link
->getMenuName() != $menu_name) {
$form_state
->setErrorByName('menu][menu_link_weight', t('The menu for one of the menu links have been changed by another user, please try again.'));
}
}
}
if ($form_state
->hasValue([
'menu',
'db_weights',
])) {
// Check that children and weights are still the same as when the form was
// loaded. Get the old values from the "hidden" form elements.
foreach ($form_state
->getValue([
'menu',
'db_weights',
]) as $link_id => $db_weight) {
$link = $menu_link_manager
->createInstance($link_id);
if ($link
->getWeight() != $db_weight) {
$form_state
->setErrorByName('menu][menu_link_weight', t('The menu link weights have been changed by another user, please try again.'));
}
}
}
if (!$form_state
->getErrors() && $form_state
->hasValue([
'menu',
'menu_link_weight',
'link_current',
'weight',
])) {
// Override the weight of the current link.
$form_state
->setValue([
'menu',
'weight',
], $form_state
->getValue([
'menu',
'menu_link_weight',
'link_current',
'weight',
]));
}
}