I'm having some trouble getting the tokens in my Drupal 9 message template to work properly. I have created and saved a message in my UI using the structure->message templates section, with a WYSIWYG text format field that contains the following:
User [user:account-name] changed details.
https://mysitename.com/user/[user:uid]
I'm concerned about the code snippet I've been using to send this message, which looks like this:
$message = Message::create([
'template' => $templateId,
'user' => \Drupal::currentUser(),
]);
When I try to send the message, the email is successfully sent, but the tokens are not being replaced and the entire message text (with token placeholders untouched) is placed in the email subject.
public function submitForm(array &$form, FormStateInterface $form_state) {
$notifier = \Drupal::service('message_notify.sender');
$templateId = $form_state->getValue('templates');
// Load all template instances.
$templateInstances = $this->entityTypeManager->getStorage('message_template')
->load($templateId);
if (!$templateInstances instanceof MessageTemplateInterface) {
$this->messenger()
->addError($this->t('No valid template has been selected.'));
return;
}
$message = Message::create([
'template' => $templateId,
'user' => \Drupal::currentUser(),
]);
$message->save();
if ($notifier->send($message)) {
$this->messenger()
->addStatus($this->t('The message has been successfully send.'));
}
else {
// If none of the above if-conditions is met, show error notification.
$this->messenger()
->addError($this->t('The message could not be send. Please contact the administrator.'));
}
I'm wondering how I can make this work with MessageTemplates and ensure that my code is in line with good Drupal practices.
Thank you for your help!