Drupal 8 — Dynamically updating pathauto URL

Deeps
2 min readMar 9, 2021

I recently came across the issue where I have article content type which can either be news or press release. In the content type, I have a select field to differenciate if it’s a news or press release. However based on the selection of news or press release, url should be dynamically generated. The URL for news should be /news/[node:title] and /press-release/[node:title].

Select field is something that I have created a while ago and which has machine name news and press.

I am using pathauto module to generate a URL alias and I don’t think I can dynamically created a URL , atleast I could not find a way to do it.

So here is what I did

function <module_name>_pathauto_alias_alter(&$alias, array &$context) {
if ($context['bundle'] === 'article' && $context['op'] == 'insert') {
/** @var \Drupal\node\Entity\Node $node */
$node = $context['data']['node'];
switch ($node->getType()) {
case 'article':
if (!empty($node->get('article_content_type')->getValue())) {
$type = $node->get('article_content_type')->getValue();

if ($type[0]['value'] === 'press') {
$alias = str_replace('/news/', '/press-release/', $alias);
}
}
}
}
}

I used the hook provided pathauto module to get field value and check if value if press and replace the value to press-release.

Note that in order to execute this hook you must define the pattern in admin/config/search/path/patterns.

So this what pathauto pattern look like in UI.

References

--

--