0

I'm attempting to use a custom made token for url alias patterns. I've been able to custom tokens using node information just fine. But it just occurred to me that I don't know how I could possibly use it with url alias patterns.

function mymodule_plugins_tokens($type, $tokens, array $data, array $options, \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata){
  $token_service = \Drupal::token();
  $replacements = array();
  if($type == 'mymodule_tokens') {
    foreach($tokens as $name => $original){
      switch($name){
        case 'current_nid':
        $node = \Drupal::routeMatch()->getParameter('node');
        $title = (!empty($node)) ? $node->id() : 'This is a test'; 
        $replacements[$original] = $title;
        break;
      }
    }
  }
  return $replacements;
}

It works fine if I'm using it on a node page. But what if I want to use it in a url alias pattern in the pathauto module?

$node = \Drupal::routeMatch()->getParameter('node');

I know here it gets the node based on the current page it's on. But if it's used in a url alias pattern it's not on any page at the time of url alias construction. I have a feeling this is possible since there are already tokens like [node:title] that work. Also is there any weird thing I can do like this?

[mymodule_tokens:current_nid[node:nid]]

Where I pass a token within a token? And if I can how would I access that extra parameter within my custom token. (p.s. I understand that my example is just getting the current_nid and that there are already tokens for it. I'm just using that as an example)

Is there anyway I can get the node from my custom token to be used in a url alias pattern?

1 Answer 1

1

You get the node from $data:

  if (!empty($data['node'])) {
    /* @var \Drupal\node\NodeInterface $node */
    $node = $data['node'];
  }

It is the responsibility of the code which calls replace() to provide the correct context (in case of Pathauto the node for which it's building the alias).

3
  • Were my previous uses of $node = \Drupal::routeMatch()->getParameter('node'); unnecessary? should $data['node'] work for every case?
    – Amy
    Nov 22, 2017 at 19:14
  • 1
    Yes, this should work in every case. If code wants to replace a token for the current node then it has to provide this node in $data when it calls replace().
    – 4uk4
    Nov 22, 2017 at 19:17
  • Of course you could generate tokens for the current node. This would be similar to the tokens which already exist for the current user. This kind of tokens don't need a context in $data, because they use the context of the current page/route. But you can't use these tokens for Pathauto.
    – 4uk4
    Nov 22, 2017 at 19:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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