7

I am trying to get the last order id for an order so that I can create an invoice and shipment automatically but I can't seems to load the correct orderId to perform the action...

Here is how I am trying to load the orderId Observer.php

$order = Mage::getModel('sales/order')->load($orderid);
$orderIncrementId = $order->getIncrementId();

If the orderId is not present throw exception

$order = Mage::getModel('sales/order')
            ->loadByIncrementId($orderIncrementId);    
if (!$order->getId()) {
        Mage::throwException("Order does not exist, for the Shipment process to complete");
    }

The problem is if I pass in a static orderId no exception is thrown

$orderIncrementId = '1100000023-4';

But when I try to load it through the Model I can't

Can anyone show me how to get the orderId for an order please?

  • What event are you using for the observer? – Vladimir Kerkhoff Aug 2 '14 at 16:53
  • @VladimirKerkhoff I am using sales_order_invoice_register for the Observer – user1704524 Aug 2 '14 at 19:10
1

The accepted answer didn't work for me. Digging into it turned out, following solution works for me:

Mage::getModel("sales/order")->getCollection()->getLastItem()->getIncrementId()
13

Get the latest order_id from the session like this:

Mage::getSingleton('checkout/session')->getLastOrderId();

Here is also another way to do it.

4

To get the last order ID in Magento:

   $orders = Mage::getModel('sales/order')->getCollection()
       ->setOrder('increment_id','DESC')
       ->setPageSize(1)
       ->getFirstItem();
    echo $orders->getEntityId()
  • 2
    This is correct, but there is an issue. getFirstItem loads the full collection. This could be a problem if you have a lot of orders. You should add a limit of 1 to the collection, to ensure that only one item is loaded. – Marius Aug 4 '14 at 10:30
  • I checked it. getFirstItem would not show all the orders information. It shows only one order information. – saravanavelu Aug 4 '14 at 10:47
  • Thanks @Marius I've ended up using Mage::getSingleton('checkout/session')->getLastRealOrderId(); but I am concious that there is a difference for orders created in Admin – user1704524 Aug 4 '14 at 10:48
  • 1
    I'm not saying it will show all the other orders information. I'm saying that it just retrieves them from the db and they are useless in this case. Check how Varien_Data_Collection::getFirstItem works. If you have 100k orders, just to retrieve the last order number this way it will take ages. – Marius Aug 4 '14 at 10:51
  • ok.That's right. – saravanavelu Aug 4 '14 at 11:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.