Reorder event on frontend
-
04-03-2021 - |
Question
I need to observe when the user is reordering an order (to delete a product), but i can't find the event, which one is it ?
Solution
You have to work on Magento\Sales\Controller\AbstractController\Reorder:: execute()
controller Action.
As execute()
as public method you use plugin instead of class rewrite.
<?php
namespace StackExchange\Magento\Plugin\Magento\Sales\Controller\AbstractController;
use Magento\Framework\Registry;
class Reorder {
/**
* @var \Magento\Framework\Message\ManagerInterface
*/
private $messageManager;
/**
* @var \Magento\Checkout\Model\Cart
*/
private $cart;
/**
* @var \Magento\Framework\Controller\Result\RedirectFactory
*/
private $resultRedirectFactory;
/**
* @var \Magento\Sales\Controller\AbstractController\OrderLoaderInterface
*/
private $orderLoader;
/**
* @var Registry
*/
private $registry;
public function __construct(
\Magento\Sales\Controller\AbstractController\OrderLoaderInterface $orderLoader,
\Magento\Framework\Controller\Result\RedirectFactory $resultRedirectFactory,
\Magento\Checkout\Model\Cart $cart,
\Magento\Framework\Message\ManagerInterface $messageManager,
Registry $registry
) {
$this->registry = $registry;
$this->orderLoader = $orderLoader;
$this->resultRedirectFactory = $resultRedirectFactory;
$this->cart = $cart;
$this->messageManager = $messageManager;
}
public function aroundExecute(
\Magento\Sales\Controller\AbstractController\Reorder $subject
){
$result = $this->orderLoader->load($subject->getRequest());
if ($result instanceof \Magento\Framework\Controller\ResultInterface) {
return $result;
}
$order = $this->registry->registry('current_order');
$resultRedirect = $this->resultRedirectFactory->create();
$cart = $this->cart;
$items = $order->getItemsCollection();
foreach ($items as $item) {
try{
$cart->addOrderItem($item) ;
}catch (\Magento\Framework\Exception\LocalizedException $e) {
if ($this->cart->getUseNotice(true)) {
$this->messageManager->addNoticeMessage($e->getMessage());
} else {
$this->messageManager->addErrorMessage($e->getMessage());
}
return $resultRedirect->setPath('*/*/history');
} catch (\Exception $e) {
$this->messageManager->addExceptionMessage(
$e,
__('We can\'t add this item to your shopping cart right now.')
);
return $resultRedirect->setPath('checkout/cart');
}
}
$cart->save();
return $resultRedirect->setPath('checkout/cart');
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange