0

I am having a problem using MYTHEME.theme file to add image field in the menu item object. I need to be able to specify an image for each menu link/item!


function HOOK_entity_base_field_info(EntityTypeInterface $entity_type) {
  $fields = [];

  if ($entity_type->id() == 'menu_link_content')
  {
   $fields['menu-image'] = BaseFieldDefinition::create('image')
   ->setLabel(t('Image shown next to menu name'))
   ->setComputed(TRUE);
  }
  return $fields;
}

I don't think that this code actually runs, I cannot see any effects!

0

Try Simple Menu Icons it showing option for menu icon.

https://www.drupal.org/project/simple_menu_icons

  • 1
    Yeah, I saw the module before, but I would actually prefer to do it without using modules. – Bassem Mohamed Sep 14 '17 at 12:09
0

Here's how I added a custom image field to my main menu link items. I added this to my custom module.

function my_custom_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;
  }
}

Flush the caches and the field should appear in the Menu Item form.

The only issue I had was that I was getting a MySQL error Column not found: 1054 Unknown column 'menu_link_image' when submitting the form. One solution to that was to add the column menu_link_content to the menu_link_content_data table but this is not a very good solution since you are altering a core Drupal db table.

I am still working on finding a better solution (e.g. using hook_form_alter to save that field to a different/custom db table). Any feedback/comment is appreciated.

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.