0

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?

1

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'.

0

Try, adding following code

$order->setState(Order::STATE_CLOSED)->setStatus($order->getConfig()->getStateDefaultStatus(Order::STATE_CLOSED));
$order->save();

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

This will change the order state and status or the order for which you are generating a credit memo.

  • Th question is, when a credit memo is created, it says, We refunded %amount online and it has order status 'Closed'. Here I want to change the order status to Canceled instead of Closed – Slimshadddyyy Oct 25 '18 at 15:27
  • @Slimshadddyyy to set the status to cancel use Order::STATE_CANCELED – Anshu Mishra Oct 25 '18 at 17:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.