2

I have a pattern set up to create the URL aliases based on a field of type list text.

the field looks like this:

selection 1|selection 1

selection 2|selection 2

How can I alter the alias so it will show something like this:

www.example.com/1-was-selected rather than www.example.com/selection-1

UPDATE: I'm using Pathauto for the patterns.

  • Not completely clear what you are asking ... are you using pathauto for the patterns ? if its your own custom module please post some code. – GiorgosK Apr 17 '18 at 15:19
  • Sorry, I forgot to mention.I'm using pathauto for the patterns. – Florin Simion Apr 17 '18 at 15:27
3

I would create a custom token and use that in my alias. I'm assuming you're using pathauto to create your aliases. This page gives a pretty good example of how to create your own token. Then you can select your token in the pathauto UI.

You can create the hook_tokens_info hook basically exactly as they've done, but replacing the "customs" with your real values. For your hook_tokens implementation, you should have access to the entity in the $data variable i.e., $data['node'] will have your node object if you're using this for nodes. From there you should be able to do something like $data['node']->field_your_list_field->getValue() to get the value of your field. Just be sure to return a $replacements array where the key is your custom_token and the value is the value to replace with, in your case this would be something like you-selected-value-X.

2

In this case I guess you should create a token in a custome module. Todo so you should implement hook_token_info() and then hook_tokens().

Or maybe you could look at hook_tokens_alter() and target the token you are actually using in your pattern to changed its rendering.

example from durpal.org:

function hook_tokens_alter(array &$replacements, array $context, \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata) {
  $options = $context['options'];

  if (isset($options['langcode'])) {
    $url_options['language'] = \Drupal::languageManager()->getLanguage($options['langcode']);
    $langcode = $options['langcode'];
  }
  else {
    $langcode = NULL;
  }

  if ($context['type'] == 'node' && !empty($context['data']['node'])) {
    $node = $context['data']['node'];

    // Alter the [node:title] token, and replace it with the rendered content
    // of a field (field_title).
    if (isset($context['tokens']['title'])) {
      $title = $node->field_title->view('default');
      $replacements[$context['tokens']['title']] = drupal_render($title);
    }
  }
}

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.