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 a senior developer with over 10 years of experience in web, app, and AI solutions. He founded this website to share his expertise, provide useful resources, and contribute to the broader developer community.

AI Assistant