18 Dec.2017

Drupal 10: How update an alias programmatically using a value from the field

drupal - update an alias programmatically

When you use the "pathauto" module, and want to make the node's URL depends on your custom field you can create a pattern using a token, for example, [node:field_private:value] and the total pattern will look like articles/[node:field_private:value]/[node:title]. However, what can you do if the field is boolean but you want to make a human path/alias? In this case, you can implement it programmatically and alter using hook_pathauto_alias_alter.

File
YOURMODULE.module
/**
 * Implements hook_pathauto_alias_alter().
 */
function YOURMODULE_pathauto_alias_alter(&$alias, array &$context) {
 
  if ($context['module'] != 'node') {
    return;
  }
 
  /** @var \Drupal\node\NodeInterface $node */
  $node = $context['data']['node'];
 
  if ($node->hasField('field_private')) {
    if ($node->get('field_private')->getString() == 1) {
      $alias = '/for-members' . $alias;
    }
    else {
      $alias = '/public' . $alias;
    }
  }
}

In the example, we are assuming your site has field_private. You can change this part of the code to your field's name.

Ruslan Piskarov

Ukraine
PHP/WEB Developer / Drupal Expert. More than 11 years of experience delivering Drupal based General Purpose solutions for different sectors such as Job Boards, Product Portfolios, Geo Coding, Real Estate solutions, E-Commerce, Classifieds, Corporate and online Magazines/Newspapers.