How to programmatically check Generate automatic URL alias

Components

If you want to programmatically check the Pathauto's Generate automatic URL alias checkbox you can do something like this:

use Drupal\pathauto\PathautoState;

$entity_type = 'node';
$entity_storage = \Drupal::entityTypeManager()->getStorage($entity_type);
$nodes = $entity_storage->loadMultiple();

foreach($nodes as $node) {
  $node->path->pathauto = PathautoState::CREATE;
  $node->save();
}

For terms just change the entity type to this:

$entity_type = 'taxonomy_term';

To uncheck the field instead of CREATE use SKIP constant:

$node->path->pathauto = PathautoState::SKIP;

In summary, the code snippets provided outline the process of programmatically toggling the automatic URL alias generation feature in Drupal using the Pathauto module. 

About the Author

Goran Nikolovski is an experienced web and AI developer skilled in Drupal, React, and React Native. He founded this website and enjoys sharing his knowledge.