Drupal 8 create node programmatically and set alias

Posted on 23/09/2019

Creating Nodes is as simple as creating other entities in Drupal 8. When you have Pathauto installed, you can also create a custom alias and pass a flag for Pathauto so it does not overwrite it with current set of rules.

This can be useful when you need to programmatically create nodes that must have a strict URL that doesn't match the Pathauto patterns.

  1. use Drupal\node\Entity\Node;
  2. use Drupal\pathauto\PathautoState;
  3.  
  4. Node::create([
  5.   'uid' => 1,
  6.   'title' => 'Test page',
  7.   'status' => 1,
  8.   'type' => 'page',
  9.   'body' => [
  10.     'value' => 'Test page with a custom alias',
  11.     'format' => 'full_html',
  12.   ],
  13.   'path' => [
  14.     'alias' => '/custom-alias',
  15.     'pathauto' => PathautoState::SKIP,
  16.   ],
  17. ])->save();