I'm currently using an event subscriber to latch onto an event from a module that creates and/or updates nodes. I'm programmatically setting the url alias based on a user inputted field by doing the following

$path = \Drupal::service('path.alias_storage')->save("/node/" . $node->id(), $url_alias, "en");

It works but when I open the node and attempt to edit it, I get the message

The alias is already in use

When I try to save it. Is there something I'm missing? Does a field on the actual node have to be edited as well?

I'm also using pathauto if that has any effect.

UPDATE: I just noticed that whenever that aliased is saved it generates 4 entries in the URL alias list.

enter image description here


Turns out whenever you perform this

\Drupal::service('path.alias_storage')->save("/node/" . $node->id(), $url_alias, "en");

It generates a new alias every time even if the path alias already exists. I was able to resolve the issue by performing checks to see if the path already exists like so:

if (!\Drupal::service('path.alias_storage')->pathHasMatchingAlias('/node/' . $node->id()) && !empty($node->id())) {
    $path = \Drupal::service('path.alias_storage')->save("/node/" . $node->id(), $url_alias, "en");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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