You are here

public function CheckoutController::checkoutRedirect in Commerce Core 8.2

Convenience method to send user to checkout via a parameter-free route.

Return value

array|\Symfony\Component\HttpFoundation\RedirectResponse The checkout page.

1 string reference to 'CheckoutController::checkoutRedirect'
commerce_checkout.routing.yml in modules/checkout/commerce_checkout.routing.yml
modules/checkout/commerce_checkout.routing.yml

File

modules/checkout/src/Controller/CheckoutController.php, line 100

Class

CheckoutController
Provides the checkout form page.

Namespace

Drupal\commerce_checkout\Controller

Code

public function checkoutRedirect() {
  $carts = $this->cartProvider
    ->getCarts();
  $carts = array_filter($carts, function ($cart) {

    /** @var \Drupal\commerce_order\Entity\OrderInterface $cart */
    return $cart
      ->hasItems();
  });

  // If there are more than one cart, or no carts, redirect to the cart page.
  if (!$carts) {
    $this->messenger
      ->addMessage($this
      ->t('Add some items to your cart and then try checking out.'));
    $redirect_url = Url::fromRoute('commerce_cart.page');
  }
  elseif (count($carts) > 1) {
    $redirect_url = Url::fromRoute('commerce_cart.page');
  }
  else {
    $cart = reset($carts);
    $redirect_url = Url::fromRoute('commerce_checkout.form', [
      'commerce_order' => $cart
        ->id(),
    ]);
  }
  return new RedirectResponse($redirect_url
    ->toString());
}