menu_link_highlight-8.x-1.x-dev/menu_link_highlight.module
menu_link_highlight.module
<?php
use Drupal\Core\Form\FormStateInterface;
/**
* Implements hook_form_BASE_FORM_ID_alter().
*/
function menu_link_highlight_form_menu_link_content_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
$account = \Drupal::currentUser();
if (!$account->hasPermission('highlight menu links')) {
return;
}
$menu_link = $form_state->getFormObject()->getEntity();
$menu_link_options = $menu_link->link ? $menu_link->link->first()->options : [];
$form['options']['highlight'] = [
'#type' => 'checkbox',
'#title' => t('Highlight'),
'#default_value' => isset($menu_link_options['highlight']) ? $menu_link_options['highlight'] : FALSE,
];
$form['actions']['submit']['#submit'][] = 'menu_link_highlight_menu_link_content_form_submit';
}
/**
* Submit function for menu add / edit form.
*/
function menu_link_highlight_menu_link_content_form_submit($form, FormStateInterface $form_state) {
/** @var \Drupal\menu_link_content\Form\MenuLinkContentForm $form_object */
$form_object = $form_state->getFormObject();
$menu_link = $form_object->getEntity();
if (!$menu_link->link) {
return;
}
$menu_link_options = $menu_link->link->first()->options ?: [];
$highlight = $form_state->getValue('highlight');
if (isset($highlight) && $highlight == TRUE) {
$menu_link_options['highlight'] = TRUE;
}
$menu_link->link->first()->options = $menu_link_options;
$menu_link->save();
}
/**
* Implements template_preprocess_menu().
*/
function menu_link_highlight_preprocess_menu(&$variables) {
foreach ($variables['items'] as $item) {
/** @var \Drupal\Core\Menu\MenuLinkDefault $menu_link */
$menu_link = $item['original_link'];
$options = $menu_link->getOptions();
if (isset($options['highlight']) && $options['highlight'] == TRUE) {
$item['attributes']->setAttribute('class', 'ml-highlight');
}
}
}
