2

I am creating a new node and then adding a new menu link. I have the code to correctly add the new node and menu link (below).

$node = Node::create([
              'type' => 'standard_page',
              'langcode' => 'en',
              'created' => REQUEST_TIME,
              'changed' => REQUEST_TIME,
              'uid' => 1,
              'title' => 'new_node',
              'body' => [
                'summary' => 'new_node',
                'value' => 'new_node',
                'format' => 'full_html',
              ]
          ]);

  $node->save();

$source = '/node/' . $node->get('nid')->value;  \Drupal::service('path.alias_storage')->save($source, '/new_node', 'en');

$link = MenuLinkContent::create([
      'title'      => $title,
      'link'       => ['uri' => 'internal:/new_node'],
      'menu_name'  => 'main',
      'weight'     => 10,
    ]);

The problem is that when I go to edit the node, "generate automatic url alias" is always ticked. So whenever I go to update the node, it destroys the alias that I have already created.

I have tried the following code.

$node->path['pathauto'] = FALSE;  
$node->save();

This doesn't seem to work in Drupal 8 as I get the following error:

InvalidArgumentException: Unable to set a value with a non-numeric delta in a list. in Drupal\Core\TypedData\Plugin\DataType\ItemList->set() (line 112 of core\lib\Drupal\Core\TypedData\Plugin\DataType\ItemList.php).

Hoe do I programatically untick the "Generate automatic URL alias" option in Drupal 8?

9

Save your node twice, once to generate the alias and the second time to turn off that option for the node.

 // Save node to generate alias
 $node->save();
 // Turn off pathauto
 $node->path->pathauto = 0;
 // Save again.
 $node->save();

Then open edit form and " Generate automatic URL alias" will be unchecked.

  • 2
    Should also work when you save just once. Set $node->path->alias = '/foo'; and ->pathauto = 0 and save. – Berdir Oct 6 '16 at 17:05
  • 1
    Thank you so much for that. I tried for ages to figure that out on my own. If only I would have asked the question sooner... – Paul Oct 12 '16 at 12:51
  • 1
    Anyone have a reference for me to look into why path is available off of the node entity and why pathauto is available off of $node->path? Are these just magic methods/properties? By reviewing the code, how would I know these exist? – powpow12 Jul 2 '18 at 14:17

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.