0

I am trying to build an order history table to display previous orders (order number/date/items ordered, etc) from a customer order in the admin order view (Magento\Sales\Block\Adminhtml\Order\View\Info). This table should list all previous orders that used the email from the current order regardless if they are a guest or have an account.

I did this in Magento 1.9 by calling the model directly in the template and running through the loop for orders and items for those orders:

<?php
$orderCollection = Mage::getModel('sales/order')->getCollection()->addFieldToFilter('customer_email',$_order->getCustomerEmail())->addFieldToSelect('*')->setOrder('entity_id', 'desc');
$recordNumber = 1;
if ($orderCollection->getSize() >= 2) { 

$orderCollection->getSelect()->limit(20);
foreach($orderCollection as $order){
$history_id = Mage::getModel('sales/order')->loadByIncrementId($order->getIncrementId())->getId();
$orders = Mage::getModel("sales/order")->load($order->getId()); 
$orderHistoryDate = $this->formatDate($order->getCreatedAtStoreDate(), 'medium', true);
$items = $orders->getAllVisibleItems();

//list orders (order number, date, status)

foreach($items as $item):

//list items in orders (qty ordered, item name, sku)

endforeach;

}
}

How can I do this with dependency injection on Magento 2?

2 Answers 2

0

You can add dependency injection like this :

protected $order;

    public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        \Magento\Sales\Model\Order $order,
        array $data = []
    ) {
        $this->order = $order;
        parent::__construct($context, $data);
    }

and get collection like:

$orderCollection = $this->order->getCollection()->addFieldToFilter('customer_email',$_order->getCustomerEmail())->addFieldToSelect('*')->setOrder('entity_id', 'desc');
$recordNumber = 1;
if ($orderCollection->getSize() >= 2) { 

$orderCollection->getSelect()->limit(20);
foreach($orderCollection as $order){
$history_id = $this->order->loadByIncrementId($order->getIncrementId())->getId();
$orders = $this->order->load($order->getId()); 
$orderHistoryDate = $this->formatDate($order->getCreatedAtStoreDate(), 'medium', true);
$items = $orders->getAllVisibleItems();

//list orders (order number, date, status)

foreach($items as $item):

//list items in orders (qty ordered, item name, sku)

endforeach;
1
  • I could not get this to work for me, the function kept throwing errors due to missing elements
    – wss web
    Commented Jan 7, 2021 at 21:01
0

How I ended up solving this:

app/code/WSS/OrderHistory/registration.php

<?php \Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE, 'WSS_OrderHistory',
__DIR__
);

app/code/WSS/OrderHistory/etc/di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Sales\Block\Adminhtml\Order\View\Info">
        <plugin name="customer_order_history" type="WSS\OrderHistory\Plugin\Block\Adminhtml\OrderHistory" sortOrder="15"/>
    </type>
</config>

app/code/WSS/OrderHistory/etc/module.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="WSS_OrderHistory" setup_version="0.0.1">
</module>
</config>

app/code/WSS/OrderHistory/Plugin/Block/Adminhtml/OrderHistory.php

<?php

namespace WSS\OrderHistory\Plugin\Block\Adminhtml;

class OrderHistory extends \Magento\Framework\View\Element\Template
{
protected $_orderCollectionFactory;
        
public function __construct(
    \Magento\Backend\Block\Template\Context $context,        
    \Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderCollectionFactory,
    array $data = []
)
{
    $this->_orderCollectionFactory = $orderCollectionFactory;
    parent::__construct($context, $data);
}

public function getOrderCollection($email) 
{
    $collection = $this->_orderCollectionFactory->create()
            ->addAttributeToSelect('*')
                    ->addFieldToFilter('customer_email', $email)
            ->setOrder('entity_id','desc');
    return $collection;
}
}

app/code/WSS/OrderHistory/view/adminhtml/layout/sales_order_view.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
<referenceBlock name="order_additional_info">
        <block class="Magento\Backend\Block\Template" name="custom_block" template="WSS_OrderHistory::order/view/history.phtml" />
</referenceBlock>
    </body>
</page>

app/code/WSS/OrderHistory/view/adminhtml/templates/order/view/history.phtml

<?php 
$currentOrder = $block->getLayout()->createBlock('\Magento\Sales\Block\Adminhtml\Order\View\Info')->getOrder(); 
$historyBlock = $block->getLayout()->createBlock('WSS\OrderHistory\Plugin\Block\Adminhtml\OrderHistory'); 
$currentEmail = $currentOrder->getCustomerEmail();
$orderCollection = $historyBlock->getOrderCollection($currentEmail);
if ($orderCollection->getSize() >= 2) { 
?>
<section class="admin__page-section">
<div class="admin__page-section-title">
<span class="title"><?php /* @escapeNotVerified */ echo __('Order History / ') ?>
<?php 
if ($orderCollection->getSize() > 20) echo 'Last 20 Orders (';
echo $orderCollection->getSize() . ' Total';
if ($orderCollection->getSize() > 20) echo ')';
?></span>
</div>
<div class="admin__page-section-content">
<?php 
echo '<div class="fieldset">';
echo '<dl>';
//orders
$orderCollection->getSelect()->limit(20);
foreach($orderCollection as $order){
    $history_id = $order->getEntityId();
    $orderHistoryDate = $order->getCreatedAt();
    $items = $order->getItemsCollection();
    
    echo '<dt>' . $orderHistoryDate . ' (Order#: <a href="' . $this->getUrl('sales/order/view', array('order_id' => $history_id)) .  '">' . ltrim(ltrim($order->getIncrementId(),"1"),"0") . '</a>) [Status: <span>' . $order->getStatus() . '</span>]</dt>';
    // items
    foreach($items as $item):
        echo '<dd>' . round($item->getQtyOrdered(), 0) . 'x - ' . $item->getName() . ' (Part#: <a href="' . $item->getProduct()->getProductUrl() . '" target="_blank">' . $item->getSku() . '</a>)</dd>';
    endforeach;
}
?>
</div>
</section>
<?php
}
?>

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.