Magento – get order totals from $order object

grand-totalorderstotals

I want to iterate over all the total models in order to get the code & values.
I have $order object and the only way I can get all the totals is using $quote object as:

$order   = Mage::getModel('sales/order')->load($orderId);
$quoteId = $order->getQuoteId();
$quote   = Mage::getModel('sales/quote')->load($quoteId);
$totals  = $quote->getTotals();
foreach ($totals as $_total) {
   echo $_total->getCode() . ' => ' . $_total->getValue() . '<br />;
}

which works fine & outputs as:

subtotal => 19.9
shipping => 10.0000
reward => 0
giftcardaccount => 0
customerbalance => -25
grand_total => 4.9
giftwrapping => 

So my main query is how to get the totals from $order object itself without using $quote. Since $quote is earlier state of $order and I doubt there might be some issues using it for the calculation.

Let me know your thoughts.

Best Answer

To sum it up, order totals aren't stored on the order object the same way as on the quote object. The reason is that the result of the dynamic quote totals are stored in the order table. You're right in it being a bad thing to get the quote totals from the order, as things like credit memos affect order totals.

The quote totals also has some extra attributes available for tax calculation that doesn't exist in the order totals procedure and that might depend on session variables.

So, bottom line: The order totals is the different values you can get*() from the order object.

The invoice and credit memo can collectTotals() because they subsequently modify the order totals (amount_paid, amount_invoiced, ..). Totals which are in fact values from sales_order_flat.

The block adminhtml/sales_order_totals used in the order view loops over getTotals('') which can cause some terminology confusion. These totals are in fact of type Varien_Object and holds static values from the database. Adding a row in there is possible but not at all as straight-forward as with the quote totals.