How to get current quote in Magento 2
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.
Table of contents
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:
1 2 3 4 |
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd"> <preference for="Magento\Checkout\Controller\Index\Index" type="MyCompany\MyModule\Controller\Index\Index" /> </config> |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
class Index extends \Magento\Checkout\Controller\Index\Index { public function execute() { //check if there are not 2 different kinds of products in cart $quote = $this->getOnepage()->getQuote(); $items = $quote->getAllItems(); //insert your custom code here //TODO return parent::execute(); } } |
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:
1 2 3 4 |
if($error) { $this->messageManager->addError(__('Mixed orders are not allowed. You can only order products of the same vendor.')); return $this->resultRedirectFactory->create()->setPath('checkout/cart'); } |
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: