Pass User object to Token::replace
문제
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?
해결책
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]);
다른 팁
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.