0

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.

2
  • You can get products using $order->getAllItems(), var_dump that data to see if you get what you need.
    – Prateek
    Commented Sep 25, 2015 at 14:09
  • I'd recommend to start using xDebug, that way you can easily analyze the available object properties. (So you won't need to write to a txt file or var_dump) Commented Sep 25, 2015 at 14:31

2 Answers 2

1

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();
}
1
$productIds = array();
$items = $order->getAllVisibleItems();
foreach ($items as $item) {
    $productIds[] = $item->getProductId();
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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