Please help with this question:

How can I hook into (in my custom module) exactly then when a private message or when a private message notification is sent?

Comments

drupalfan2 created an issue. See original summary.

artem_sylchuk’s picture

Status: Active » Needs review

hook_ENTITY_TYPE_insert - you should be able to catch the new message on hook_private_message_insert(). As far as I remember you may have thread information missing on this stage.

Alternatively you can check hook_ENTITY_TYPE_update - you should be able to catch the new message in hook_private_message_thread_update():

/**
 * Implements hook_ENTITY_TYPE_update().
 */
function hook_private_message_thread_update(PrivateMessageThreadInterface $thread) {
  if ($thread->isNew()) {
    return;
  }

  $messages_count = $thread->get('private_messages')->count();
  /** @var PrivateMessageThreadInterface $original */
  $original = $thread->original;
  $old_count = $original->get('private_messages')->count();
  // If new message added.
  if ($messages_count && $old_count < $messages_count) {
    // Get last message.
    $messages = $thread->getMessages();
    /** @var PrivateMessageInterface $message */
    $new_message = end($messages);

    // Allow to hook on a new message.
    \Drupal::moduleHandler()
      ->invokeAll('on_new_message', [$thread, $new_message]);
  }
}

Probably worth to include hook_on_new_message that into a module's code.

drupalfan2’s picture

I found a solution by myself few days ago:

hook_entity_insert(EntityInterface $entity) {
  if ($entity->getEntityTypeId() == 'message') { 
    $typeid = $entity->getEntityTypeId();
    if ($typeid == 'message') {
      if ($entity->bundle() == 'private_message_notification') {
        $receiver_uid = $entity->uid->target_id;
        // do the things here
      }
    }
  }

  // also works but there are less variables to use:
  if ($entity->getEntityTypeId() == 'private_message' {
    // do the things here if the needed variables are available
  }
}

So the Message module helps to solve this.

Has your solution some advantages?

artem_sylchuk’s picture

Status: Needs review » Fixed

That's great that you found a solution

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.