\Drupal::service('notifications_widget.logger') is NULL in EventSubscriber

Created on 3 May 2023, over 1 year ago

Problem/Motivation

I'm trying to get a custom notification logged when a FLAG is triggered. The flag must be interacted with as an event. So I'm using Drupal's Event Subscriber System to log a notification on flagging. Here's my code below...

<?php

namespace Drupal\custom_notifications\EventSubscriber;

use Drupal\flag\FlagServiceInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Drupal\flag\Event\FlagEvents;
use Drupal\flag\Event\FlaggingEvent;

/**
 * Flag event subscriber.
 */
class FlagSubscriber implements EventSubscriberInterface {

  /**
   * The flag service.
   *
   * @var \Drupal\flag\FlagServiceInterface
   */
  protected $flag;

  /**
   * Constructs a FlagSubscriber object.
   *
   * @param \Drupal\flag\FlagServiceInterface $flag
   *   The flag service.
   */
  public function __construct(FlagServiceInterface $flag) {
    $this->flag = $flag;
  }

  public function onFlag(FlaggingEvent $event) {

    $flagging = $event->getFlagging();
    
    $flagLike = $this->flag->getFlagById('like');

    $flaggingUser = $event->getFlagging()->getOwner();
    
    // If flag is LIKE report
    if ($flagging->getFlagId() === $flagLike->id()) {

      $entity = $flagging->getFlaggable();
      $entityAuthor = $entity->getOwner();


      $message = [
        'id' => $entity->id(),
        'bundle' => 'report',
        'content' => 'test - user liked your report',
        'content_link' => $entity->toUrl()->toString(),
      ];
      
      $notificationService = \Drupal::service('notifications_widget.logger');
      $notificationService->logNotification($message, 'update', $entity, $entityAuthor->id());

      ddl($notificationService);

    }

  }

  public static function getSubscribedEvents() {
    $events = [];
    $events[FlagEvents::ENTITY_FLAGGED][] = ['onFlag'];
    return $events;
  }

}

Flag triggers correctly... unfortunately, the $notificationService variable (\Drupal::service('notifications_widget.logger')) returns as NULL.

Is there a different way it needs to be called to work within the Event Subscriber system?

πŸ’¬ Support request
Status

Closed: works as designed

Version

2.0

Component

Code

Created by

πŸ‡ΊπŸ‡ΈUnited States chucksimply

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Production build 0.71.5 2024