I would like to delete order's invoice, credit memo & shipment programmatically.
How to achieve this by passing only order id?
Magento Stack Exchange is a question and answer site for users of the Magento e-Commerce platform. It only takes a minute to sign up.
Sign up to join this communityThere are few steps are required for this.
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 using getInvoiceCollection()
As you want run delete operation then you should set $this->registry->register('isSecureArea', true);
Get Shipment collection from Order object using getShipmentsCollection()
Get credit memo collection from Order object using getCreditmemosCollection()
<?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(); } } } }