0

I added a field to the menu_link_content entity, but am unable to set the value of this field in my my_module.links.menu.yml.

Here is my hook_entity_base_field_info:

/**
 * Implements hook_entity_base_field_info_alter().
 */
function my_module_admin_menu_entity_base_field_info_alter(&$fields, EntityTypeInterface $entity_type) {
  if ($entity_type->id() != 'menu_link_content') {
    return;
  }


  // Create the base field definition for the allowed roles. This field will
  // reference user entities.
  $fields['my_module_admin_menu__show_role'] = BaseFieldDefinition::create('entity_reference')
    ->setName('my_module_admin_menu__show_role')
    ->setTargetEntityTypeId('menu_link_content')
    ->setLabel(t('Roles able to see the menu link'))
    ->setCardinality(FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED)
    ->setSetting('target_type', 'user_role')
    ->setDisplayOptions('form', [
      'type' => 'options_buttons',
      'weight' => 0,
    ]);
}

In my my_module.links.menu.yml, I provide a menu link like so:

my_module_admin_menu.article:
  title: 'Article'
  menu_name: admin-per-user-role
  url: internal:/node/add/article
  parent: my_module_admin_menu.create
  bundle: menu_link_content
  my_module_admin_menu__show_role:
    settings:
      target_type: user_role
      handler: default
    target_id:
      - authenticated

The link shows up, but doesn't show the field: enter image description here

When a link is added via the menu UI, the field is shown: Field is shown when link is added via the menu UI

1

Menu links discovered in *.links.menu.yml are not menu link content entities and therefore don't contain the field you have added to the entity. If you want to fill this field with data programmatically, create an instance of the entity:

$link = MenuLinkContent::create([
  'title' => 'Article',
  'menu_name' => 'main',
  'bundle' => 'menu_link_content',
  'link' => [['uri' => 'entity:node/1']],
  'custom_field' => 'custom content',
]);
$link->save();

The content of *.links.menu.yml seems a bit odd. The title field is the only required value and you can see that the link is discovered and the title is displayed in the screenshot. The other values are optional. Check the documentation about which values you can use in this file https://www.drupal.org/docs/8/api/menu-api/providing-module-defined-menu-links


The field seems to be for some kind of access control. You shouldn't do this in the menu link. Instead control the permissions of the target. Menu items are only displayed for users who can access the target.

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.