3

This is how i create my node :

    $value= array(
                'type' => 'page',              
                'title'=>"First node",
                'body' => array(
                    'value' => "test",
                    'format' => 'full_html',
                ),
);

$nodeEntity=\Drupal::entityTypeManager()
            ->getStorage('node')
            ->create($value);

        $nodeEntity->save();

This work fine.

But i try to give a menu parent to this node.

i try that :

$value= array(
            'type' => 'page',              
            'title'=>"First node",
            'body' => array(
                'value' => "test",
                'format' => 'full_html',
            ),
            'menu'=>array(
             'title'=>"First node",
             'menu_parent'=>6,
             'description' => '',
             'enabled'=>1

        ),

);

i set the field menu because it's the name of the field in the node edit form. But for the nodeEntity, this field doesn't exist.

How can i give a parent menu id to my node ?

UPDATE

if i set menu_link instead of menu, i got no error i still can't see the menu on the node.

1 Answer 1

2

After look into the database and some test, this is how i add a menu to my node on the creation or on node update :

For this example, i load a node :

  $nodeEntity=\Drupal::entityTypeManager()
            ->getStorage('node')
            ->load(312);

After you create the link :

$menu_link = MenuLinkContent::create([
    'title' => 'name of your menu',
    'link' => ['uri' => 'internal:/node/' . $nodeEntity->id()],
    'menu_name' => 'main',
    'expanded' => TRUE,
]);

$menu_link->save();

If you want add a parent to your menu just add this in $menu_link :

$menu parent is the uuid of the parent menu

'parent' => 'menu_link_content:' . $menuParent,

Then you need to update menu_link_content_data

  $this->database->update('menu_link_content_data')
            ->fields([
                'link__uri' => 'entity:node/'.$nodeEntity->id(),
            ])
            ->condition('id', $menu_link->id())
            ->execute();

The link between the menu and the node is the link__uri, you need to tell him to reference the entity node.

After that, you ll see your menu link on your node.

I haven't find better solution with Drupal API for now.

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.