I also needed this redirect (to the cart, but it could also work for the checkout).
There are a few possibilities that appeared to work, but not predictable:
- Rules redirect based on saving an order item
- Event listener on: commerce_order.place.post_transition
- Submit handler on the 'add to cart' action.
All these solutions may appear to work at first sight but after further testing it appeared that the redirect was sometimes done before adding the item to the cart.
Therefore I fall back on the solution given by Egbert Bleyenburg with the difference that I used hook_preprocess_status_messages(). So I skip the step of rendering the status message and don't use the javascript.
Call your function in hook_preprocess_status_messages():
function hook_preprocess_status_messages(&$variables) {
redirect_order_to_cart($variables['message_list']['status']);
}
Above is just an example, in production you'd like to have a condition to check if you are on the correct page and if the status messages are set.
Below the custom function you call to redirect:
function redirect_order_to_cart(array $status_messages) {
$cart_path = Url::fromRoute('commerce_cart.page')->getInternalPath();
foreach ($status_messages as $message) {
// If we have a status message containing a href with the cart path we know
// that it's the order item confirm message. This is the moment we want to
// redirect to the cart.
if (
$message instanceof Markup
&& strpos($message->jsonSerialize(), 'href="/' . $cart_path) !== FALSE
) {
// Setting the redirect.
$response = new RedirectResponse(\Drupal::service('url_generator')
->generateFromRoute('commerce_cart.page'));
$response->send();
break;
}
}
}