:::: MENU ::::

Magento 2 programmatically add custom order status

Magento 2 programmatically add custom order status

Today we talk about how in Magento 2 programmatically add custom order status. This tutorial includes set custom order status and also set the default magento order status too. You have to inject Magento\Sales\Model\Order to set order status. So let start with our example.

Dependency Injection

protected $orderFactory;
public function __construct(
           
        \Magento\Sales\Model\OrderFactory $orderFactory,

    ) {


        $this->orderFactory = $orderFactory;

    }

public function customOrderStatus(){
        $orderId = 3;
        $order = $this->orderFactory->create()->load($orderId);
        $state = $order->getState();
        $status = 'custom_cancel';
        $comment = 'This is test comment';
        $isNotified = false;
        $order->setState($state);
        $order->setStatus($status);
        $order->addStatusToHistory($order->getStatus(), $comment);
        $order->save();
}

Object Manager

        $orderId = 3;
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $order = $objectManager->create('\Magento\Sales\Model\Order')->load($orderId);
        $state = $order->getState();
        $status = 'custom_cancel';
        $comment = '';
        $isNotified = false;
        $order->setState($state);
        $order->setStatus($status);
        $order->addStatusToHistory($order->getStatus(), $comment);
        $order->save();
Author: Qaisar Satti
Category: Magento 2
Last Modified: July 12, 2018


So, what do you think ?