If you use the last development version of commerce, and look for file commerce\modules\cart\src\Form\AddToCartForm.php
which lives under the Drupal\commerce_cart\Form
namespace, you can see that cart_id was set, and it is the order ID too.
$form_state->set('cart_id', $cart->id());
Therefore, in hook_form_alter()
, we can get the order ID (the cart ID).
$order_id = $form_state->get('cart_id');
The complete code would be this.
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
/**
* Implements hook_form_alter().
*/
function <MY_MODULE>_form_alter(&$form, FormStateInterface $form_state, $form_id) {
// Add to cart form id for product 5 is: commerce_order_item_add_to_cart_form_commerce_product_5
// Then it's enough to check $form_id contains the string 'commerce_order_item_add_to_cart_form_commerce'
if(strpos($form_id, 'commerce_order_item_add_to_cart_form_commerce') !== false) {
$form['actions']['submit']['#submit'][] = '_redirect_to_checkout';
}
}
// Callback for form submission
// @see hook_form_alter().
function _redirect_to_checkout(&$form, FormStateInterface $form_state) {
/** @var \Drupal\commerce_order\Entity\OrderInterface $cart_id */
$cart_id = $form_state->get('cart_id');
$url = Url::fromRoute('commerce_checkout.form',
['commerce_order' => $cart_id]
);
$form_state->setRedirectUrl($url);
}