1

I created a node programmatically with the following code.

$data = array(
  'type' => 'inception_article',
  'title' => $msg->name,
  'body' => array(
    'value' => $msg->body,
    'format' => 'full_html'
  )
);

$node = Node::create($data);
$node->save();

I would now also like to create the menu link for the node, but I cannot figure out how to do that in Drupal 8.

How can I programmatically create a menu link for a node I create?

2 Answers 2

1

You can save menu link Separately using the below code on node save.

 $menu_link = MenuLinkContent::create(array(
      'title' => 'Menu Title', // Menu title is your title of menu, in this case node title
      'path' => '/path/to/node', // Menu link something like '/node/'.$nid, replace $nid with your node id
      'menu_name' => 'navigation',
      'weight' => 0,
      'bundle' => 'menu_link_content',
 ));

 $menu_link->save(); 
1
  • 1
    Yes Its creating the menu link, and working fine. But while editing the node its not present under "Menu Settings". How can i Do this ? Commented Jan 11, 2017 at 8:17
1

To have the menu also on the node entity, you need to pass the link uri as entity:

MenuLinkContent::create([
  'title' => 'Menu title', // Menu title is your title of menu, in this case node title
  'link' => ['uri' => 'entity:node/' . $node->id()],
  'menu_name' => 'main',
  'weight' => 0,
])->save();

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.