2

I've the following code (sample) that runs on Cron and sends SMS to users.

$token = \Drupal::token();
$message = Hey, [current-user:account-name];
$message_value = $token->replace($message);
  

When cron run, Getting the SMS text as 'Hey Anonymous' This works correctly on site when user logins in. but not on cron.

So I tried to pass the user object to replace the token like follows but that doesn't work. Getting same result.

use Drupal\user\Entity\User;
$user = User::load($uid);
$message_value = $token->replace($message,['user' => $user]);

There are so many nodes created using this token. So I can't edit them all with new/custom token. So Is there any way to replace the user token, without writing a custom token? The other workaround is to use str_replace like follows, but there might exists other user tokens in the same text. so not preferable.

  $message_value = str_replace('[current-user:account-name]', $name, $message);

Any suggestions?

2 Answers 2

2

The current-user token will always take its data from the current user, you can't override it with parameters. See user_tokens:

if ($type == 'current-user') {
  $account = User::load(\Drupal::currentUser()
    ->id());
  $bubbleable_metadata
    ->addCacheContexts([
    'user',
  ]);
  $replacements += $token_service
    ->generate('user', $tokens, array(
    'user' => $account,
  ), $options, $bubbleable_metadata);
}

If you need to control the account object used for the token, use user instead

$message = 'Hey, [user:account-name]';
$message_value = $token->replace($message, ['user' => $account]);
1
  • 1
    Brilliant! as always, you saved my time. Thank you! Nov 20, 2020 at 10:38
0

Your approach

$user = User::load($uid);
$message_value = $token->replace($message,['user' => $user]);

doesn't work because of user.tokens.inc:153 (as of 8.8.11):

  if ($type == 'current-user') {
    $account = User::load(\Drupal::currentUser()->id());
    $bubbleable_metadata->addCacheContexts(['user']);
    $replacements += $token_service->generate('user', $tokens, ['user' => $account], $options, $bubbleable_metadata);
  }

So, depending on where you call the $token->replace, you may try to tweek the \Drupal::currentUser()->id() by re-setting it temporary.

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.