cancel
Showing results for 
Search instead for 
Did you mean: 

set order state programmatically

set order state programmatically

$newState = Order::STATE_COMPLETE;
$order->setState($newState)->setStatus(Order::COMPLETE);
$order->save();

 I use the obove code to change the state of an order from processing to complete.
Actually the state is changed to "" (empty), not to COMPLETE.

 

Any ideas?

 

Regards,
Gunther

4 REPLIES 4

Re: set order state programmatically

Hello @kornblumenapo

 

 

use Magento\Sales\Model\Order;$orderId = 1;$objectManager = \Magento\Framework\App\ObjectManager::getInstance();$order = $objectManager->create('\Magento\Sales\Model\Order') ->load($orderId);$orderState = Order::STATE_PROCESSING;$order->setState($orderState)->setStatus(Order::STATE_PROCESSING);$order->save();

If it will help you then give us kudoes or accept as solution.


Problem solved? Click Kudos & Accept as Solution!
Sunil Patel
Magento 2 Certified Professional Developer & Frontend Developer

Re: set order state programmatically

Try with below code and let me know,

$newState = \Magento\Sales\Model\Order::STATE_COMPLETE;
$order->setState($newState)->setStatus(\Magento\Sales\Model\Order::STATE_COMPLETE);
$order->save()
If Issue Solved, Click Kudos/Accept As solutions. Get Magento insight from
Magento 2 Blogs/Tutorial

Re: set order state programmatically

$order->save() is deprecated. It will work for now but it's been deprecated for a while.

Re: set order state programmatically

<?php

class MyCustomClass
{
    /**
     * @var \Magento\Sales\Api\OrderRepositoryInterface
     */
    private $orderRepository;

    /**
     * MyCustomClass constructor.
     *
     * @param \Magento\Sales\Api\OrderRepositoryInterface $orderRepository
     */
    public function __construct(
        \Magento\Sales\Api\OrderRepositoryInterface $orderRepository
    ) {
        $this->orderRepository = $orderRepository;
    }

    /**
     * @param int $orderId
     *
     * @return bool
     */
    public function setOrderComplete($orderId)
    {
        try {
            /** @var \Magento\Sales\Api\Data\OrderInterface $order */
            $order = $this->orderRepository->get($orderId);
            $order->setState(\Magento\Sales\Model\Order::STATE_COMPLETE);
            $this->orderRepository->save($order);
            
            $result = true;
        } catch (\Exception $e) {
            $result = false;
        }
        
        return $result;
    }
}