Sales : Orders :How to add custom order status programmatically
-
15-04-2021 - |
Question
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;
}
La solution
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();
Autres conseils
Firstly you must create a custom status and assigned a state like processing. in an upgradeData or InstallData
$statusData = array('status'=> 'custom', 'state'=> 'processing', 'label' => 'custom state');
try {
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$statusFactory = $objectManager->create('\Magento\Sales\Model\Order\Status\StatusFactory')->load($orderId);
$status = $statusFactory->create(['data' => $statusData]);
// Firstly, create the status
$status->save();
// Secondly, assign the status to state
$status->assignState($statusData['state']);
} catch (CouldNotSaveException $exception) {
$this->logger->critical($exception);
}
i created:
$order = $objectManager->create('\Magento\Sales\Model\Order')->load($order_number);
$order->setState(\Magento\Sales\Model\Order::STATE_CANCELED, true);
If i check the status programmaticaly with
$order = $objectManager->create('\Magento\Sales\Model\Order')->load($order_number);
return $order->getState();
the status is canceled but if i see to frontend it not changed.
Why?
Licencié sous: CC-BY-SA avec attribution
Non affilié à magento.stackexchange