How to Change Order State to Processing from Complete Programmatically

order-statusorders

i'm try to make a order's state to processing from complete. here is the code

class TempName_HelloWorld_IndexController extends Mage_Core_Controller_Front_Action
{
    public function indexAction()
    {
     $this->loadLayout(array('default'));
     $this->renderLayout();

     $order = Mage::getModel('sales/order');
     $order->loadByIncrementId(100000041);
     $order->setState(Mage_Sales_Model_Order::STATE_PROCESSING, true, 'Gateway has authorized the payment.');
     $order->save();
    }
}

?>

the above code can update the order state from pending/pending payment to processing, but i can't update the order state from complete to processing. Anyone can what is the problem?

Best Answer

By default you can't adjust the order state when it's complete. This is because this state is protected.

A closer look at the code tells us why:

When you call setState the following is triggered in the Mage_Sales_Model_Order class.

public function setState($state, $status = false, $comment = '', $isCustomerNotified = null)
{
    return $this->_setState($state, $status, $comment, $isCustomerNotified, true);
}

Which, as you can see bubbles directly down to _setState.

protected function _setState($state, $status = false, $comment = '',
    $isCustomerNotified = null, $shouldProtectState = false)
{
    // attempt to set the specified state
    if ($shouldProtectState) {
        if ($this->isStateProtected($state)) {
            Mage::throwException(
                Mage::helper('sales')->__('The Order State "%s" must not be set manually.', $state)
            );
        }
    }
    $this->setData('state', $state);

    // add status history
    if ($status) {
        if ($status === true) {
            $status = $this->getConfig()->getStateDefaultStatus($state);
        }
        $this->setStatus($status);
        $history = $this->addStatusHistoryComment($comment, false); // no sense to set $status again
        $history->setIsCustomerNotified($isCustomerNotified); // for backwards compatibility
    }
    return $this;
}

In which all states that are passed in are checked using the isStateProtected method.

Check that method tells us that the 'complete' state is protected. Thus is being blocked for further updates.

public function isStateProtected($state)
{
    if (empty($state)) {
        return false;
    }
    return self::STATE_COMPLETE == $state || self::STATE_CLOSED == $state;
}

When an order is complete, usually it's invoiced and shipped etc. So why would you want to adjust the state back to 'processing'? That would mean the order is not shipped anymore, while a shipment is probably already created. That will probably give you some trouble further down the road.

For now at least you know why you can't adjust the order. Hopefully this helps you!