Magento 2: How to delete order's invoice, credit memo & shipment programmatically?
-
07-10-2020 - |
题
I would like to delete order's invoice, credit memo & shipment programmatically.
How to achieve this by passing only order id?
解决方案
There are few steps are required for this.
Load order by Order Factory
Inject the factory class \Magento\Sales\Model\OrderFactory
on __construct
class.for getting order.
Then order get by order id
$order = $this->orderFactory->create()->load($orderId);
Get Invoice collection from Order object
Get Invoice collection from Order object using getInvoiceCollection()
As you want run delete operation then you should set $this->registry->register('isSecureArea', true);
Get Shipment collection from Order object
Get Shipment collection from Order object using getShipmentsCollection()
Get credit memo collection from Order object
Get credit memo collection from Order object using getCreditmemosCollection()
code:
<?php namespace [YournameSapce]; class DeleteorderInvoiceetc { protected $order; protected $redirectFactory; protected $registry; public function __construct( ........ \Magento\Sales\Model\OrderFactory $orderFactory, \Magento\Framework\Registry $registry ) { ...... $this->orderFactory = $orderFactory; $this->registry = $registry; } public function Order(){ $orderId = 'xyz'; if(!$this->order){ $this->order = $this->orderFactory->create()->load($orderId); } return $this->order; } public function deleteInvoices(){ if(!$this->Order()){ return; } if($this->registry->registry('isSecureArea')){ $this->registry->unregister('isSecureArea'); } $this->registry->register('isSecureArea', true); $_invoices = $this->Order()->getInvoiceCollection(); if($_invoices){ foreach($_invoices as $invoice){ $invoice->delete(); } } } /* * Shipemrnt delete */ public function deleteShipments(){ if(!$this->Order()){ return; } if($this->registry->registry('isSecureArea')){ $this->registry->unregister('isSecureArea'); } $this->registry->register('isSecureArea', true); $_shipments = $this->Order()->getShipmentsCollection(); if($_shipments){ foreach($_shipments as $_shipment){ $_shipment->delete(); } } } /* * Credit memo delete */ public function deleteCreditmemos(){ if(!$this->Order()){ return; } if($this->registry->registry('isSecureArea')){ $this->registry->unregister('isSecureArea'); } $this->registry->register('isSecureArea', true); $_creditmemos = $this->Order()->getCreditmemosCollection(); if($_creditmemos){ foreach($_creditmemos as $_creditmemo){ $_creditmemo->delete(); } } } }