Score:0

Send message to users with certain field enabled with Message Module

ru flag

I would like to send/display a message in a block view on user profile when some content type node is created, but only if that user has a certain custom field enabled on their profile.

I have created the message template and used hook_node_insert() to send a message but the problem is it sends this message to all users if I(as an admin user) have the custom field enabled or doesn't if I have it disabled.

My hook looks like this:

function notification_node_insert($node) {
  $ids = \Drupal::entityQuery('user')
    ->condition('field_notify_me_about_new_events', '1')
    ->execute();

  $users = User::loadMultiple($ids);
  foreach ($users as $user) {
    $message = Message::create(['template' => 'new_event', 'uid' => $node->getOwnerId()]);
    $message->set("field_node_ref", 'uid');
    $message->save();
  }
}

The problem with my code is also that the block displays multiple identical messages (one for each iteration).

How would I be able to achieve that only users with the custom field enabled would receive the message?

Jaypan avatar
de flag
So you only want to show the message to the current user if they have that field enabled?
leymannx avatar
ne flag
Curious if it's maybe better to do the message logic with Queue API. I mean depending on how many users you expect to loop through later, of course.
Bass-Ninja avatar
ru flag
@Jaypan yes I do. The message should only be shown to those who have the field enabled.
Jaypan avatar
de flag
The current user, or all users with the field enabled? These are different things.
Bass-Ninja avatar
ru flag
@Jaypan All users with the field enabled.
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.