I would like to make a feature request and ask for allowing tokens in redirects.

For example, for a certain tax vocab on my site (vocab), every term will always redirect.

So if I could set a redirect from vocab/[taxonomy:term] to vocab2/[term:name] it would be very helpful in that I wouldn't have to manually create a redirect for every term to every proper page.

Just a thought if you were looking for some more features to implement.

Comments

davidwhthomas’s picture

I added support for user tokens using the drupal_alter call in the redirect module.

In another module I added

/**
 * Implements hook_redirect_alter
 */
function EXAMPLE_redirect_alter(&$redirect){
  global $user;
  // Only act if user token in redirect path
  if(!empty($redirect->redirect) && strpos($redirect->redirect, '[user') !== FALSE){
    if(!user_is_logged_in()){
      // Bounce via login back to source path
      $redirect->redirect = 'user/login';
      $redirect->redirect_options['query'] = array('destination' => $redirect->source);
    }else{
      // Apply user tokens to redirect path
      $redirect->redirect = token_replace($redirect->redirect, array('user' => $user));
    }
  }
}

I added a redirect like

from: my-subscription
to: user/[user:uid]/subscription

and it works fine :)

I can even make a link like

user/login?destination=my-subscription

and the user is bounced there to their user profile subpage
If the user is already logged in, they go staight to the dest page.
If the user is logged out, they get bounced via user/login and onto the dest page

Cheers,

DT

henrijs.seso’s picture

Thanks for the code. Still, would be welcome addition.

zastapmnie’s picture

Hello
How excatly You "added support for user tokens using the drupal_alter call in the redirect module".
I asking because i'm completly green in programming :_)

Best Regards

thejamesjones’s picture

Dave,

Where exactly did you add this? in the redirect.module file? between what lines?

James

davidwhthomas’s picture

I added the code in a custom module, replace "EXAMPLE_" with the module name.

More info:

DT

spessex’s picture

Hi David

I came across your post with much interest and have used your code and have created the module to use tokens on a redirect.

I am currently trying to use it to redirect from the edit page of a Profile2 profile e.g. 'profile-live_surveys/[profile2:user:uid]/edit' but it doesn't appear to work for me.

I'm trying to get to the bottom of this but for a starter wanted to know if the 'URL Redirects' page still 'counts' the redirects if you are using a redirect with a token or does it not get counted?

I've tried to test it with some other token but for the life of me can't think of one to use/test to see if it's working. My code is as follows as simply replaces EXAMPLE as you stated - my module is called ste_survey_edit_redirect (please note I have excluded the closing php statement as advised by Drupal for modules):

<?php
/**
* Implements hook_redirect_alter
*/
function ste_survey_edit_redirect_redirect_alter(&$redirect){
global $user;
// Only act if user token in redirect path
if(!empty($redirect->redirect) && strpos($redirect->redirect, '[user') !== FALSE){
if(!user_is_logged_in()){
// Bounce via login back to source path
$redirect->redirect = 'user/login';
$redirect->redirect_options['query'] = array('destination' => $redirect->source);
}else{
// Apply user tokens to redirect path
$redirect->redirect = token_replace($redirect->redirect, array('user' => $user));
}
}
}

pere orga’s picture

Issue summary: View changes

I've closed #1446236: Is there a way to use a token in the redirect? as a duplicate of this one

pere orga’s picture

Status: Active » Postponed

This would be a great addition. However, It would be so complex to implement that it may be a good idea to create a Redirect Token contrib module instead.

That's why I think this ticket should be postponed, at least until a stable version is released. Imho

ndf’s picture

Just made a module based on the snippets above:
https://www.drupal.org/project/redirect_token

dave reid’s picture

Component: Code » Documentation
socialnicheguru’s picture

Version: 7.x-1.x-dev » 8.x-1.0

can this be updated to Drupal 8?

kenorb’s picture

Example code for Drupal 8:

use Drupal\redirect\Entity\Redirect;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Drupal\Component\Utility\UrlHelper;

/**
 * Implements hook_redirect_response_alter().
 */
function EXAMPLE_redirect_response_alter(RedirectResponse $response, Redirect $redirect) {
  $uri = $redirect->getRedirect()['uri'];
  if (!empty($uri) && strpos($uri, '[') !== FALSE) {
    $uri = \Drupal::token()->replace($uri);
    $external = UrlHelper::isValid($uri, TRUE);
    $redirect->setRedirect($external ? $uri : explode('/', $uri, 2)[1]);
    $response->setTargetUrl($redirect->getRedirectUrl()->setAbsolute()->toString());
  }
}

To use hook_redirect_response_alter, you need to apply patch from #2909182: API migration: No hook_redirect_alter() in 8.x first.

Testing scenario:
1. Create a redirect with the following parameters:
FROM: token/test
TO: /success/[current-page:url:relative]
2. Now, when you go to /token/test, you should be redirected to /success/token/test.

Here is the use case example: How to dynamically redirect user from /foo/X to /bar/X?

chris matthews’s picture

Version: 8.x-1.0 » 8.x-1.x-dev
alternativo’s picture

Hi,
I tried patch #25 both with version 1.4 and dev, but no way to make tokens work in all your suggestions and also test.
Version 1.4: It seems not to work token functionality at all, it do not covert any token, the url remain of this kind '%5Bcurrent-page%3Aurl%3Arelative%5D'
Dev version: It recognises the [] so the url takes: [current-page%3Aurl%3Arelative]
Do anyone can help me...think I did something wrong beside the patch and hook_redirect_response_alter funcion
thanks

angrytoast’s picture

For @alternativo in #14 and any one who might stumble on this thread. There is a new patch (as of 2020-01-30) in https://www.drupal.org/project/redirect/issues/2909182#comment-13444722 (#29) that should be compatible with the latest 8.x-1.x redirect version.

I have verified it is working, you have to:
1. Apply the patch to the module, this enables a net new alter hook, hook_redirect_response_alter
2. You must implement a hook function in a custom module that you control. @kenorb's comment in https://www.drupal.org/project/redirect/issues/1331582#comment-12873791 is a good starting point. The redirect module does not care about tokens by default, so it is the site owner's responsibility to implement custom behavior.

alternativo’s picture

Hi @angrytoast, thanks I will test the new patch asap, and I will send test results.
Meanwhile I solved using redirect in .htaccess file, but I think it will be better to use redirect module, as the .htaccess file is replaced on modules/core updates :/

andrew answer’s picture

Hi, maybe someone will be interested in my solution. I use Pathauto module installed, and use this code:

$path = $GLOBALS['base_url'] . \Drupal::service('pathauto.generator')->createEntityAlias($user, 'return');

to generate path with pattern /owner/[user:field_user_city:value]/[user:uid]-[user:field_user_firstname:value]. Then I create redirect with

      $custom_links[] = [
        'url' => $path,
        'lastmod' => $sitter_profile_changed,
        'priority' => '0.8',
        'changefreq' => 'weekly',
      ];
redzeuf’s picture

StatusFileSize
new1.02 KB

Here is a proposition to go forward on doing a patch feature that take care of tokens in the "sub_path" and "url destination". You can find those fields at this path /admin/config/search/redirect/domain and the Tokens list available here: /admin/help/token

Please be aware that I only take care of "global" token like for exemple "site:", "language:"... So I do not pass any array $data and by the way I don't care of all token cases. Lot of tokens won't be replaced.
Read the documentation about the token replace function for more information.

redzeuf’s picture

Just a review of the header of the patch because past one doesn't apply... + I renamed the file for better naming convention.