Drupal 8 WorkBench EventSubscriber Example

Drupal 8 Event subscriber example for work bench moderation module.
say you want to do some thing when a work bench state changes ... this will get the logged in user vs the node content creator and get there enmails etc.

Service File:

services:
  test_even_subscriber.default:
    class: Drupal\test_even_subscriber\EventSubscriber\DefaultSubscriber
    arguments: ['@current_user']
    tags:
      - { name: event_subscriber }


Drupal\test_even_subscriber\EventSubscriber\DefaultSubscriber.php

<?php

namespace Drupal\test_even_subscriber\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\EventDispatcher\Event;
use Drupal\Core\Session\AccountInterface;

/**
 * Class DefaultSubscriber.
 *
 * @package Drupal\test_even_subscriber
 */
class DefaultSubscriber implements EventSubscriberInterface {

  /**
   * The current user.
   *
   * @var currentUser
   */
  protected $currentUser;

  /**
   * Constructor.
   */
  public function __construct(AccountInterface $current_user) {
    $this->currentUser = $current_user;
  }

  /**
   * {@inheritdoc}
   */
  static function getSubscribedEvents() {
    $events['workbench_moderation.state_transition'] = ['test'];
    return $events;
  }

  /**
   * This method is called whenever the workbench_moderation.state_transition event is
   * dispatched.
   *
   * @param GetResponseEvent $event
   */
  public function test(Event $event) {
    // Logged in user id.
    $logged_in_user_id = $this->currentUser->id();

    dump($event);
    // Get Node.
    $node = $event->getEntity();

    $applicant_user = $node->get('uid')->entity;
    $application_user_id = $applicant_user->id();
    if ($logged_in_user_id == $application_user_id) {
      // No Notifications needed.
    }
    else {
      // Send a notification only in state .
      $states_to_notify_applicant = [
        'state_one',
        'state_two',
        'state_whatever'
      ];
      $new_state = $event->getStateAfter();
      if (in_array($new_state, $states_to_notify_applicant)) {
        // Send applicant something.
      }

    }

    // User Emails From a Filed node ...
    $node_email = $node->field_email->value;
    $applicant_system_email = $applicant_user->get('mail')->value;
    // Figure out what email to use.
    dump($applicant_system_email);
    dump($node_email);
    // Get logged in user mail.
    $logged_in_user_email = $this->currentUser->getEmail();
    dump($logged_in_user_email);



    // Work bench state before.
    dump($event->getStateBefore());
    // Work bench state After.
    dump($event->getStateAfter());

    drupal_set_message('Event workbench_moderation.state_transition thrown by Subscriber in module test_even_subscriber.', 'status', TRUE);
  }

}
Category: