Magento2 – How to Restore Stock After Cancel Order

cancel-ordersmagento2manage-stockstock

I am working on Magento 2.3.5 p-1

I have created a custom module that adds a mass action to the sales order grid, through a controller this action changes the order status to "customCancel" and the order state to Canceled using order->setState(\Magento\Sales\Model\Order::STATE_CANCELED); but does not return the order stock to inventory.

Can someone guide me on how to do this? Thanks in advance

Best Answer

I have found the solution, I share it in case it is useful to someone in the future.

To return the stock to the inventory, the simplest way is to cancel the order, then in my execute function of my controller I add:

foreach ($collection->getItems() as $order) {

                $order->cancel(); //first i cancel the order
                $order->setStatus($customCancel); //then I assign my custom status which I have in a variable
                $this->orderRepository->save($order); //and finally I save the order

          }

When canceling the order it is no longer necessary to assign the state CANCELED

Related Topic