0

I've added two new fields to the menu item form (admin/structure/menu/item/{ID}/edit):

function modulename_entity_base_field_info(\Drupal\Core\Entity\EntityTypeInterface $entity_type) {
  $fields = [];

  if($entity_type->id() == 'menu_link_content') {
    $fields['show_mobile'] = \Drupal\Core\Field\BaseFieldDefinition::create('boolean')
      ->setLabel(t('Show in mobile menu bar.'))
      ->setDescription(t('Toggles the display of the menu item in the menu bar at the bottom of pages in mobile view.'))
      ->setDisplayOptions('form', [
        'type' => 'boolean_checkbox',
        'weight' => '0',
        'settings' => [
          'display_label' => TRUE,
        ],
      ])
      ->setDisplayConfigurable('form', TRUE);

    $fields['svg_icon'] = \Drupal\Core\Field\BaseFieldDefinition::create('string')
      ->setLabel(t('Mobile Menu Bar SVG Icon'))
      ->setDescription(t('Select the icon you want the menu item to use in the mobile menu bar.'))
      ->setDisplayOptions('form', [
        'type' => 'string',
        'weight' => '0',
        'settings' => [
          'display_label' => TRUE,
        ],
      ])
      ->setDisplayConfigurable('form', TRUE);
  }

  return $fields;
}

But now I run into the issue, that I only need these fields for the main navigation menu, and thus want to remove or hide these on all other menu item forms.

Preferably I would like to keep it all to the module that adds the fields, and not have to create a custom admin theme just to visually hide them.

What should I look at to figure this one out? I've tried googling a lot of different combinations of the question, but have yet to find anything that remotely looks like a solution.

Many thanks in advance to anyone who can point me in the right direction.

1

hook_entity_base_field_info will add fields to the entire entity. If you want to hide the fields in specific forms, you will have to use a form alter to hide the fields. The following code might be what you are looking for.

/**
 * Implement hook_form_FORM_ID_alter();
 */
function modulename_form_menu_link_content_menu_link_content_form_alter(&$form, FormStateInterface $form_state) {
  $name = $form_state->getFormObject()->getEntity()->getMenuName();
  if ($name !== 'my-menu') {
    $form['show_mobile']['#access'] = FALSE;
    $form['svg_icon']['#access'] = FALSE;
  }
}

Change my-menu with the menu machine name of the only menu that you want the fields to appear on.

  • Thanks a ton, was not expecting such a detailed answer, you saved me a lot of time :) – Dion S. Jensen Apr 26 '17 at 6:19

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.