How to add a role to specific product type customer? I'm trying to add a user role (darshan) to customer buying product from a specific product type (darshan_session), using an EventSubscriber in a custom module.

For now, I'm stuck with the following code, where I need still to check the product type and to load the user from the ID.

namespace Drupal\commerce_darshan\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Drupal\state_machine\Event\WorkflowTransitionEvent;
use Drupal\user\UserAuthInterface;
use Drupal\user\UserInterface;

class CommerceDarshanEventSubscriber implements EventSubscriberInterface {

  public static function getSubscribedEvents() {
    $events = ['commerce_order.place.post_transition' =&gt; 'onOrderPlace'];
    return $events;
  }

  public function onOrderPlace(WorkflowTransitionEvent $event) {
    $event-&gt;getEntity()-&gt;getCustomerId();

    $user-&gt;addRole('darshan');
  }
}


As this is my first custom module on D8, any help would be welcome.
You're using $user before setting it. You have a CustomId it looks like, but have not created an instance of User with that Id.

Perhaps something like this:

public function onOrderPlace(WorkflowTransitionEvent $event) {
  $userId = $event-&gt;getEntity()-&gt;getCustomerId();
  $user = \Drupal\user\Entity\User::load($userId);
  $user-&gt;addRole('darshan');
  \Drupal::logger('mycustom_module_name')-&gt;notice('Role "darshan" added to user ' . $user-&gt;getDisplayName());
}