0

I have a large website with 240 urls that need to be updated. I would like to do this programmatically to avoid making errors. I created the following function which seems to work. There seems to be a good bit of complexity here for what I am trying to accomplish. Is there a simplier way to update the url of a node?

function alias_replace($path, $lang, $new_alias) {

  $path_alias_manager = \Drupal::entityTypeManager()->getStorage('path_alias');

  $alias_objects = $path_alias_manager->loadByProperties([
    'path'     => $path,
    'langcode' => $lang
  ]);
  
  foreach($alias_objects as $alias_object) {
    $alias_object->delete();
  }

  $path_alias_manager->create([
    'path'     => $path,
    'alias'    => $new_alias,
    'langcode' => $lang
  ])->save();

}
4
  • 1
    Why not use Pathauto to bulk generate?
    – Kevin
    Aug 10, 2021 at 1:59
  • The urls follow the website structure for content that we authored. Here is a sample url: /daily-devotions/genesis-1to11/in-the-beginning. The content has been translated into Spanish and Chinese. Chinese urls are mostly English. The Spanish urls are in Spanish without the accent marks. I'm not sure there is a Pathauto solution.
    – Greg Sims
    Aug 10, 2021 at 2:10
  • You should be able to set a Pathauto pattern for each language. (in Drupal 8) If you also have the transliteration module, and the token module installed, I think you be able to use the Pathauto solution for the use case you described.
    – Rick B
    Aug 10, 2021 at 13:29
  • Thanks for the feedback on Pathauto -- I will look into this further. Is the code I included above the best way to update the url for a node without Pathauto?
    – Greg Sims
    Aug 10, 2021 at 13:32

1 Answer 1

3

A slightly simpler way I found is that you don't need to delete and create the alias object as you can just update its object properties in place with ->save() like this:

function alias_replace($path, $lang, $new_alias) {

  $path_alias_manager = \Drupal::entityTypeManager()->getStorage('path_alias');

  $alias_objects = $path_alias_manager->loadByProperties([
    'path'     => $path,
    'langcode' => $lang
  ]);
  
  foreach($alias_objects as $alias_object) {
    $alias_object->alias = $new_alias;
    $alias_object->save();
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.