Score:0

Update Alias Programmatically

us flag

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();

}
Kevin avatar
in flag
Why not use Pathauto to bulk generate?
Greg Sims avatar
us flag
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.
Rick B avatar
cn flag
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.
Greg Sims avatar
us flag
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?
Score:2
gf flag

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();
  }
}
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.