1

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' => 'onOrderPlace'];
    return $events;
  }

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

    $user->addRole('darshan');
  }
}

As this is my first custom module on D8, any help would be welcome.

1
  • You don't have a valid user object and even if you were, you aren't saving the user object..
    – Kevin
    Nov 2, 2018 at 14:37

1 Answer 1

1

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->getEntity()->getCustomerId();
  $user = \Drupal\user\Entity\User::load($userId);
  $user->addRole('darshan');
  \Drupal::logger('mycustom_module_name')->notice('Role "darshan" added to user ' . $user->getDisplayName());
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.