Magento 2 get current quote
This shows you how to get current quote from your Magento 2 shot. This is often needed if you want manipulate a cart before creating an order from it. With a current quote object you have access all items and do some checks or manipulations with them.
Magento 2 get current quote
Simplest of all solutions is to overload controller files that are called during checkout, for example \Magento\Checkout\Controller\Index\Index. For this you need to add two files to your customer Magento 2 module:
- di.xml1234<?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>
This is to register your overloaded controller class. You should change MyCompany and MyModule to your needs. - Controller/Index/Index.php12345678910111213class 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//TODOreturn parent::execute();}}
From this controller you can get a cart (quote) object from onepage. To get all cart items, you only need to call getAllItems() method.
Every time you start Magento 2 checkout, your shop will compute your custom code. This is the perfect solution if you want to check if your cart and all products meets your special needs. If you encounter an error (for example a not valid combination of products in cart), you may display an error message and return to cart. This can be done with following lines of code:
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 messageManager registers you error message that is displayed next time a frontend site is loaded. To redirect, you can use a resultRedirectFactory object with “checkout/cart” as destination.
Conclusion
It is easy to get current quote in Magento 2 if you use the correct object. Overloading or overriding controllers is often the best way to add customer code to Magento 2 checkout.
1 Response
[…] Magento 2 get current quote by MAGEMASTER […]