Magento – Magento 2 – Change order status when Credit memo created

creditmemomagento2order-statusorders

Below code to create credit memo programmatically

public __construct(
    \Magento\Sales\Model\Order $order,
    \Magento\Sales\Model\Order\CreditmemoFactory $creditmemoFactory,
    \Magento\Sales\Model\Order\Invoice $invoice,
    \Magento\Sales\Model\Service\CreditmemoService $creditmemoService,
    array $data = []
) {
    parent::__construct($data);
    $this->order = $order;
    $this->creditmemoFactory = $creditmemoFactory;
    $this->creditmemoService = $creditmemoService;
    $this->invoice = $invoice; 
}

public function refundCode()
{
    $order = $this->order;
    $order->load(10);

    $invoices = $order->getInvoiceCollection();
    foreach ($invoices as $invoice) {
        $invoiceincrementid = $invoice->getIncrementId();
    }

    $invoiceobj = $this->invoice->loadByIncrementId($invoiceincrementid);
    $creditmemo = $this->creditmemoFactory->createByOrder($order);

    // Don't set invoice if you want to do offline refund
    $creditmemo->setInvoice($invoiceobj);

    $this->creditmemoService->refund($creditmemo); 
}

Here the function refund located at path vendor\magento\module-sales\Model\Service\CreditmemoService.php does the work, but I could not figure out how it sets the Order Status to Closed?

When a credit memo is created, it changes order status to Closed. How do I change it to Canceled?

Best Answer

It can be done by,

sales_order_creditmemo_save_after

observer, it will trigger once a credit memo has been created. In this observer you can check with order status label

if ($order->getStatusLabel() == 'Closed')

then you can change it to 'Canceled'.