0

I want to add a menu link to a menu programmatically. Here is my code

MenuLinkContent::create([
      'title' => 'Example link',
      'link' => ['uri' => 'internal:/node'],
      'menu_name' => 'main',
    ])->save();

But it gives me the following error

PHP Fatal error:  Call to a member function get() on a non-object in /var/www/drupal8/core/modules/menu_link_content/src/Plugin/Menu/MenuLinkContent.php on line 105

Is there any way to add menu links to a menu programmatically?

3

I was using the wrong namespace. Use the following namespace

use Drupal\menu_link_content\Entity\MenuLinkContent;

and then the following code will work.

MenuLinkContent::create([
      'title' => 'Example link',
      'link' => ['uri' => 'internal:/node'],
      'menu_name' => 'main',
    ])->save();
|improve this answer|||||
  • Where would one put this? IN the controller? Dot-module file? – Rick Jul 21 '17 at 15:57

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.