Magento2 Sales Order – How to Add Custom Order Status Programmatically

magento2magento2.2order-statusPHPsales-order

I need to add custom status for an order programatically
I have below controller file to save order status.
I need to add custom status as cancel initiated.Provide me a solution…

Controller file

public function execute()
    {
        $orderId = 3;
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $order = $objectManager->create('\Magento\Sales\Model\Order')->load($orderId);
        $order->addStatusHistoryComment('');
        $orderState = Order::STATE_PROCESSING;
        $order->setState($orderState)->setStatus(Order::STATE_PROCESSING);// Here I need to add custom status as Cancel initiated
        $order->save();

        $resultPage = $this->_resultPageFactory->create();
        return $resultPage;
    }

It is failed to fetch or change the status dropdown
enter image description here

Best Answer

First create new status Stores > Order Status and set the code for status custom_cancel and use below code

        $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(); 
Related Topic