Magento 1.9 – How to Get Product Details in Observer (Order Save)

event-observermagento-1.9product

i am trying to get all the product in a order. i have the order details in my observer but i don't know how to get the product details from it. i have the following coding in my observer

public function getProducts($observer){
 $order = $observer->getEvent()->getOrder();
 $data = $order->getData();
 $dumpFile = fopen('observer_working.txt', 'w+'); // file is creating
 fwrite($dumpFile, 'Sample text');
 return $this;
}

As you can see i am creating a txt file when order is placed. and it is working. and i have the order details also. but i am unable get the product id from it.

i need following data from the order details

1) Order id.

2) array of product id which is available in the order. (only product id is enough)

please help me to get those data.

Best Answer

The order id is easy, as most models in Magento implement the getId() method:

$orderId = $order->getId();

Depending on whether you want all line items (configurable products will have 2) or just those that are visible, you can get a collection of order_items as follows:

$orderItems = $order->getAllItems(); // All line items

or

$orderItems = $order->getAllVisibleItems(); // All visible line items

These can then be iterated to get the product IDs:

$ids = array();
foreach ($orderItems as $item) {
    $ids[] = $item->getId();
}
Related Topic