With pathauto enabled, how can we programmatically set “Generate automatic URL alias” to TRUE for existing nodes, using PHP or SQL?

I have tried all patches and PHP or SQL solutions suggested and nothing has worked for the latest D8 + pathauto releases.

After having studied various options, I believe this could be the fastest way to do it:

use Drupal\node\Entity\Node;

$query = \Drupal::entityQuery('node');
$query->condition('status', 1);
$query->condition('type', 'my_content_type');
$entity_ids = $query->execute();

foreach ($entity_ids AS $nid) {

$node = Node::load($nid);
$node->set("path", ["pathauto" => TRUE]);	//this line is not doing anything
$node->save();
}

No errors but when I check my nodes after the execution of this code, they still have the "Generate automatic URL alias" disabled/invisible.

Comments

David Fiaty created an issue. See original summary.

David Fiaty’s picture

Title: set generate automatic URL alias programmatically » Set generate automatic URL alias programmatically
Issue summary: View changes
Berdir’s picture

Status: Active » Fixed

You should use the constant, but something like that should work.

\Drupal\pathauto\Tests\PathautoNodeWebTest::testNodeState() has code that tests both saving to explicitly generate aliases and to not do that.

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.

TOMY MOHAN’s picture

use Drupal\pathauto\PathautoState;
$contentTypes = [ 'library', 'news', 'events'];
    foreach ($contentTypes as $contentType) {
      $nodeQuery = \Drupal::entityQuery('node');
      $nodeQuery->condition('type', $contentType);
      $entity_ids = $nodeQuery->execute();
      if (isset($entity_ids) && !empty($entity_ids)) {
        foreach ($entity_ids AS $entity_id) {
          $node = Node::load($entity_id);
          $node->path->pathauto = PathautoState::CREATE;
          $node->save();
        }
      }
    }