2

Is there a way to add field(s) to menu links in Drupal 8? Like an image field to output above certain links?

6
  • Could you specify the use case a bit ? The image field should come from a related node somehow or ? Mar 23, 2017 at 22:53
  • When creating a menu link in the menu admin, there would be a field for attaching an image to it, for rendering in say, a mega menu.
    – Kevin
    Mar 23, 2017 at 22:54
  • Ah, i see. So you need something like drupal.org/project/menuimage or drupal.org/project/menu_icons for D8. Mar 23, 2017 at 23:30
  • @OlegVidenov I only see D7 versions for both of those modules...
    – No Sssweat
    Mar 24, 2017 at 2:54
  • yes, for now I also don't see any D8 ports of those modules as well. Mar 24, 2017 at 9:30

1 Answer 1

1

Add this code to your custom module:

function my_module_entity_base_field_info(\Drupal\Core\Entity\EntityTypeInterface $entity_type) {
  if ($entity_type->id() === 'menu_link_content') {
    $fields['menu_link_image'] = BaseFieldDefinition::create('image')
      ->setLabel(t('Menu link image'))
      ->setDescription(t('Upload the image related to this menu item'))
      ->setDisplayOptions('form', array('type' => 'string', 'weight' => 0));

    return $fields;
  }
}

Then use hook_update_n to update the schema of the menu_link_content_data table. Run update.php, flush caches and the new field should appear on all the Add/Edit menu item form.


In case someone wants to simply add a text field, boolean etc, simply edit BaseFieldDefinition::create('image') and change it to BaseFieldDefinition::create('string') or BaseFieldDefinition::create('boolean') etc

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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