You are here

function message_subscribe_example_user_insert in Message Subscribe 8

Implements hook_user_insert().

File

message_subscribe_example/message_subscribe_example.module, line 184
Holds hook implementation for the Message Subscribe Example module.

Code

function message_subscribe_example_user_insert(User $account) {
  $subscribers = \Drupal::service('message_subscribe.subscribers');

  // Create a custom subscriber list to notify administrators about new users.
  // This is an end run around the normal flag subscription system.
  // Hard-coding 'uids' in $subscribe_options will cause message_subscribe to
  // skip other subscribers and send to just this list, so this allows us
  // to create a custom subscription list for this purpose.
  // This is not needed if you're automatically adding administrators in either
  // hook_subscribe_get_subscribers() or hook_subscribe_get_subscribers_alter(),
  // or if you're automatically flagging administrators. It's just another
  // illustration of things that can be done.
  $query = \Drupal::entityQuery('user')
    ->condition('status', 1);
  $query
    ->condition('roles', 'administrator');
  $admin_uids = $query
    ->execute();
  $flags = [
    'subscribe_user',
  ];
  $notifiers = [
    'email',
  ];
  $notify_options = [];
  $subscribe_options = [
    'notify message owner' => FALSE,
    'uids' => [],
  ];
  foreach ($admin_uids as $uid) {
    $subscribe_options['uids'][$uid] = new DeliveryCandidate($flags, $notifiers, $uid);
  }

  // Queue messages to our custom list of subscribers.
  $message = Message::create([
    'template' => 'user_register',
    'uid' => $account
      ->id(),
  ]);
  $message
    ->set('field_user', $account);
  $message
    ->set('field_published', $account
    ->isActive());
  $message
    ->save();
  $subscribers
    ->sendMessage($account, $message, $notify_options, $subscribe_options);
}