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);