문제

How to Get the latest 5 order in home page in Magento2 with all order details?

Any help would be appreciated.

도움이 되었습니까?

해결책

Try this,

Create a helper and add the below code to it,

Helper path be like

app/code/Vendor/Module/Helper/Data.php

<?php
namespace Vendor\Module\Helper;
class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
public function __construct(
    \Magento\Sales\Model\OrderFactory $orderFactory
) {
    $this->orderFactory = $orderFactory;
}
public function getCollection()
{
    $collection = $this->orderFactory->create()->getCollection()->setOrder('entity_id', 'DESC');
    $collection->setPageSize(5)->setCurPage(1);
    return $collection;
}
}

then in your phtml you can call like below

$order = $this->helper('Vendor\Module\Helper\Data')->getCollection();
foreach($order as $items){
    echo "Entity Id :". $items->getEntityId();
    echo "Order Status :". $items->getStatus();
}

you can call any of the phtml in the home page to get this information.

To call a phtml only on home page follow the below steps

create a cms_index_index.xml in the below path

app/code/Vendor/Module/view/frontend/layout/cms_index_index.xml

then add the below code to it

<?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>
   <referenceContainer name="content">
        <block class="Magento\Framework\View\Element\Template"  name="sales_total" template="Vendor_Module::total.phtml">
        </block>
    </referenceContainer>
</body>
</page>

Vendor_Module - this should you namespace_modulename

And also place total.phtml in the below path

app/code/Vendor/Module/view/frontend/templates/total.phtml

Hope this helps.

다른 팁

protected $_checkoutSession; protected $_orderFactory; protected $_scopeConfig;

public function __construct(
    \Magento\Checkout\Model\Session $checkoutSession,
    \Magento\Sales\Model\OrderFactory $orderFactory,
    \Magento\Framework\View\Element\Context $context
) {
    $this->_checkoutSession = $checkoutSession;
    $this->_orderFactory = $orderFactory;
    $this->_scopeConfig = $context->getScopeConfig();
}


// Use this method to get ID    
public function getRealOrderId()
{
    $lastorderId = $this->_checkoutSession->getLastOrderId();
    return $lastorderId;
}

public function getOrder()
{
    if ($this->_checkoutSession->getLastRealOrderId()) {
         $order = $this->_orderFactory->create()->loadByIncrementId($this->_checkoutSession->getLastRealOrderId());
    return $order;
    }
    return false;
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 magento.stackexchange
scroll top