Score:1

Replace MessageTemplate with token value and send the message

in flag

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!

id flag
Reading between the lines I think there is a contributed module involved. Could you please edit the question, including a link to that module? Please share a larger code sample because, for example, the current code does not indicate what `$notifier` or `$this->messenger` is, if `$this->messenger` is in fact relevant to the question. So we need precisely the amount of code to illustrate your question, but without any extraneous code.
Adamssef avatar
in flag
Thank you for your comment. The code is within a class that extends FormBase and from there I have access to Drupal\Core\Messenger\MessengerTrait.
id flag
The reason I asked about contributed modules is that structure->message templates—if you are referring to menus—isn’t part of Drupal Core, and so knowing what module provides that feature could lead to an answer to this question. The service object `message_notify.sender` also is not a part of Drupal Core.
id flag
It appears you are using https://www.drupal.org/project/message_notify. Have you seen its example module?
Adamssef avatar
in flag
Yes, I checked it. From what I figured I should try using sth like this: $message->set('field_user_reference', \Drupal::currentUser()->id()); but I am getting an exception saying that field field_user_reference is unkown. And it's true there's very little fields I can access in my message object.
Score:0
kn flag

Message templates are configurable. You can add fields in them using the standsrd fields ui. Then you should be able to access the fields from code and use the tokens from the template.

Adamssef avatar
in flag
I initially upvoted this answer, but it turned out that is not the case. When writing this question I had already had message with tokens in place that was created in the UI.
Score:0
in flag

It turned out that tokens sounding like "current user" or "current date" worked just fine. The problem was that tokens starting from "user:...." needed an additional context of a user that wasn't provided by default.

To me the solution was to apply this patch: https://www.drupal.org/project/message/issues/2981259.

And then modify the code slightly so that it looks like this:

$message = Message::create([
  'template' => $templateId,
  'uid' => $entity->id(),
]);

$message->setOwner($entity);
$message->save();

Perhaps someone would find it useful. Cheers.

I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.