Question

On the order confirmation page, I am trying to pull all the values of the items involved in the completed purchase, so they can be injected into a tracking iFrame. I found this code online, but it didn't work in my file for some reason:

    $objectManager = $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $cart = $objectManager->get('\Magento\Checkout\Model\Cart'); 

    //get quote items collection
    $itemsCollection = $cart->getQuote()->getItemsCollection();

    //get array of all items what can be display directly
    $itemsVisible = $cart->getQuote()->getAllVisibleItems();

    //get quote items array
    $items = $cart->getQuote()->getAllItems();

    foreach($items as $item) {
        echo 'ID: '.$item->getProductId().'<br />';
        echo 'Name: '.$item->getName().'<br />';
        echo 'Sku: '.$item->getSku().'<br />';
        echo 'Quantity: '.$item->getQty().'<br />';
        echo 'Price: '.$item->getPrice().'<br />';
        echo "<br />";            
    }
    $block_methods = $item;

So then I tried to restart by simply assigning \Magento\Checkout\Model\Cart a variable name in two different ways:

$cart = get_called_class("\Magento\Checkout\Model\Cart");

and

$cart = get_class("\Magento\Checkout\Model\Cart");

but those methods both caused the page to freeze. Can anybody help explain what I am doing wrong?

Was it helpful?

Solution

Use below code in success page

<?php
$lid = $this->getOrderId();
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$order = $objectManager->create('Magento\Sales\Model\Order')->load($lid);
$items=$order->getAllItems();
foreach($items as $_item):
   $_product = 
$objectManager->create('Magento\Catalog\Model\Product')->load($_item->getProductId());
        echo 'ID: '.$_product->getId().'<br />';
        echo 'Name: '.$_product->getName().'<br />';
        echo 'Sku: '.$_product->getSku().'<br />';
        echo 'Quantity: '.$_item->getQtyOrdered().'<br />';
        echo 'Price: '.$_item->getPrice().'<br />';
        echo "<br />"; 

endforeach;
?>

OTHER TIPS

Success page Only appear when you successfully Placed an order so instead of getting data from Quote you should get data from order id because an order is already placed once you have an order id you can load it and get its data in your success.phtml file.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top