How to get current quote in Magento 2

- E-Commerce, Magento 2

Magento 2 import export debug log

In the following article, we shed light on how to get a current quote in Magento 2. To be more exact – from your Magento 2 shot. Why does one need this action? It is mainly utilized for manipulating a cart before creating an order from it. A current quote object provides you with access to all items and enables doing some checks or manipulations with them. You can find more useful tips here: Magento 2 Cookbook.

'

How to get current quote in Magento 2

According to Magento2 Blog, the most straightforward solution is to overload controller files called during checkout. For instance, you can work with Magento\Checkout\Controller\Index\Index. Add the following two files to your customer Magento 2 module:

di.xml

Use the following code snippet:

It lets you register the overloaded controller class. Don’t forget to replace MyCompany and MyModule with your values.

Controller/Index/Index.php

Here, you need to use the following code to get the current quote in Magento 2:

Now, you can get a cart/quote object from onepage from this controller. Call the getAllItems() method to get all cart items.

Error message

Your shop will compute the custom code for every checkout. Thus, you can effortlessly check whether your cart and all products meet specific needs or not. If you discover an error, display an error message. Use the following code snippet replacing ‘Mixed orders are not allowed. You can only order products of the same vendor.’ with your own message:

A message manager registers your error message so that it is displayed next time the frontend is loaded. Use a resultRedirectFactory object with “checkout/cart” as a destination to redirect customers.

Final Words

As you can see, there is nothing difficult in getting a current quote in Magento 2. You only need to use the correct object. The best way to add custom code to Magento 2 checkout is to overload or override controllers. For further information, follow this link: How to get current quote in Magento 2.

'