Magento – What is the difference between getAllVisibleItems() and getAllItems()?

Before we start with answer of the question, I would like to explain what are these functions. These bothe functionas are used to get all order items,

// load form order ID
$order_id = 1234;
$order = Mage::getModel("sales/order")->load($order_id);
OR
// Get current order ID
$order_id = Mage::getSingleton('checkout/session')->getLastRealOrderId();
$order = Mage::getModel('sales/order')->loadByIncrementId($order_id);
//$order->getSubtotal() ; $order->getGrandTotal() ;
$items = $order->getAllItems(); OR $order->getAllVisibleItems();
$itemcount=count($items);
foreach ($items as $itemId => $item)
{
    $item->getName();
    $item->getPrice();
    $item->getSku();
    $item->getProductId();
    $item->getQtyOrdered(); //$item->getQtyToInvoice();
}

Above code will give all the information of order and ordered items.

Now lets get back to the main question. Let’s look at the code of both methods first,

public function getAllItems()
{
    $items = array();
    foreach ($this->getItemsCollection() as $item) {
       if (!$item->isDeleted()) {
          $items[] = $item;
       }
    }
    return $items;
}
public function getAllVisibleItems()
{
    $items = array();
    foreach ($this->getItemsCollection() as $item) {
       if (!$item->isDeleted() && !$item->getParentItemId()) {
          $items[] = $item;
      }
    }
    return $items;
}

From the code we can see, The only difference is getAllVisibleItems() has an additional check for each item that is,

!$item->getParentItemId()

Which will allow parent item only, It means if you have Configurable Product in your order, getAllVisibleItems will show you only the parent item while getAllItem will show both products.

$order->getAllItems() refers to the all items parent and it’s child (ref: configurable product and it’s child items)
getallitems

$order->getAllVisibleItems() refers to the Parent items only (Ref: configurable product only)
getallvisibleitems

Conclusion, If you need to show order product or do some kind calculation on total ordered items getAllVisibleItems is more preferable.

Advertisements

One thought on “Magento – What is the difference between getAllVisibleItems() and getAllItems()?

  1. Pingback: How to get correct quantity for child product in cart | DL-UAT

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s