2

I want to add a description field to my menu and and use it in front.

I managed to have a text_format field for my description (in /admin/structure/menu/manage/main) but when I click on save, that field is empty.

function HOOK_form_alter(&$form, $form_state, $form_id) {
  if ($form_id != 'menu_edit_form') {
    return false;
  }
  $form['field_menu_content'] = array(
   '#type' => 'text_format',
   '#title' => t('Description'),
   '#format' => 'full_html',
  );
}
2

This question is similar to https://stackoverflow.com/q/39288049/4629065

Try out Menu Item Extras module for Drupal 8 from Drupal.org projects site https://www.drupal.org/project/menu_item_extras.

For more info take a look the next answer https://stackoverflow.com/a/46728856/4629065

1

In hook_form_alter() add a submit function:

$form['#submit'][] = 'my_module_menu_edit_submit';

Where you store the field:

function my_module_menu_edit_submit($form, FormStateInterface $form_state) {
  $config = \Drupal::service('config.factory')->getEditable('mymodule.settings');
  $config->set('main_content', $form_state->getValue('field_menu_content'))
    ->save();
}

The main menu is hard coded in the settings name. If you want this to work for all menus, you can try to get the menu name from the form. I did not investigate where you can get it.

When you build the form field you also need to get the field value from config. More information: https://www.drupal.org/docs/8/api/configuration-api/simple-configuration-api

  • Thank you it's working! There was few typos, I've post the working code. – Tib Jan 10 '17 at 14:55
1

Here is the complete working solution from @4k4 answer:

function mymodule_form_alter(&$form, $form_state, $form_id) {
  if ($form_id != 'menu_edit_form') {
    return false;
  }
  $config = \Drupal::service('config.factory')->getEditable('mymodule.settings');
  $field_menu_content = $config->get('field_menu_content');
  $form['field_menu_content'] = array(
   '#type' => 'text_format',
   '#title' => t('Description'),
   '#default_value' => $field_menu_content['value'],
   '#format' => 'full_html',
  );
  $form['actions']['submit']['#submit'][] = 'mymodule_menu_edit_submit';
}

function mymodule_menu_edit_submit($form, $form_state) {
  $config = \Drupal::service('config.factory')->getEditable('mymodule.settings');
  $config->set('field_menu_content', $form_state->getValue('field_menu_content'))->save();
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.