Drupal Commerce 2: Go to checkout after adding to cart
There are times when you want to redirect a customer after some event. For example, for some types of products you may want to redirect the customer directly to checkout instead of leave them on the current page (as is the default). While there is an issue (still open as of 2017-12-07) in Drupal Commerce to allow order types to have no cart, we can accomplish this functionality by responding to the CART_ENTITY_ADD event.
Two things need to happen:
Listen for the Cart module’s CART_ENTITY_ADD event
Respond to the Symfony Kernel’s RESPONSE event
Step 1: Listen for the CartEvents::CART_ENTITY_ADD event
So we create a listener and look for the order item or purchased entity we are interested in.
Now we are listening for the cart event and adding our checkout url to the current request. Next we need to listen for the KernelEvents::RESPONSE event where we can set a RedirectResponse using our url.
Step 2: Respond to the KernelEvents::RESPONSE event
The KernelEvents::RESPONSE event is dispatched by the Symfony HTTP kernel early in the page request life cycle and allows subscribers to alter the response that is sent back to the user. In our case, we want the response to be a redirect.
So we add another listener:
Finally, we need to register our listener with the container by adding it to our module’s .services.yml file.
Step 3: Add the event subscriber to the module’s .services.yml file
The event subscriber needs to be be tagged as an event_subscriber, and it needs the request_stack service to be injected (see core.services.yml). So we add the following to my_module.services.yml: