3

I read through the Drupal 8 menu_api documentation in drupal.org. The example guide lists an option to create menu links and insert them into an existing menu. How does one create menu itself first and insert the menu links afterwords?

I used the entitytype manager based on the other answer in stackexchange, but going yml way is recommended. Any pointers?

use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\menu_link_content\Entity\MenuLinkContent;

\Drupal::entityTypeManager()
->getStorage('menu')
->create([
 'id' => 'test',
 'label' => 'test menu',
'description' => 'test test',
 ])
 ->save();

Using routes below to create the links:

 test.home:
 title: 'Home'
 url: 'test.url'
 menu_name: test
 weight: 1
| improve this question | | | | |
1

If you have a feature where you need to create a menu whenever something happens, using the code should be just fine.

I prefer using the static create method on the entity object \Drupal\menu\Entity\Menu::create, but the manager is fine as well.

If you are creating menu's on your development environment as part of setting up your drupal site, I would advice using config export/import. If you use drush, you can make it part of the deployment to import configuration so production always reflect the configuration you have saved. I prefer to do things like this, but for small sites it might be a bit overkill.

| improve this answer | | | | |
  • 2
    Please, could you add a short example with code where I can see create function parameters and use statements to make it work? Thanks! – Roger Nov 26 '16 at 15:38

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.