0

I want to display on a .phtml file a list of order items for a logged in user. I don't want to use object manager.

I can get the id of the logged in user ($customerId) on the phtml.

I have created a block class

namespace 'moduleNameSpace';
class Orders extends \Magento\Framework\View\Element\Template
{
    protected $_customerSession;
    protected $_orderCollectionFactory;
    protected $orders;
    public function __construct(
            \Magento\Backend\Block\Template\Context $context,
            \Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderCollectionFactory,
            \Magento\Customer\Model\Session $customerSession,
             array $data = []
        ) {

    $this->_orderCollectionFactory = $orderCollectionFactory;

    parent::__construct($context, $data);
    $this->_customerSession = $customerSession;
}



public function getLoggedinCustomerId() {
    if ($this->_customerSession->isLoggedIn()) {
        return $this->_customerSession->getId();
    }
    return false;
}


public function getOrders($customerId)
{

    if (!$this->orders) {
        $this->orders = $this->_orderCollectionFactory->create()->addFieldToSelect(
            '*'
        )->addFieldToFilter(
            'customer_id',
            $customerId
        )->setOrder(
            'created_at',
            'desc'
        );
    }
    return $this->orders;
}
}

and then on the .phtml template i have

$customerId = $block->getLoggedinCustomerId();
$orders = $block->getOrders($customerId);
foreach ($orders as $order) {
foreach ($order->getAllVisibleItems() as $item){
   ...
}
}

The problem is that foreach is not working, even when I want to count the number of orders for example

foreach ($orders as $order) {                                                                 
$orderCount++ ;
}
echo $orderCount;

How can I get all order items? I think the problem may be on the block class

3

2 Answers 2

1

app/code/VendoreName/ModuleName/Block

OrderList.php

<?php

namespace VendoreName\ModuleName\Block;

use Magento\Framework\View\Element\Template;

class OrderList extends Template
{
    protected $_orderCollectionFactory;
    protected $orderRepository;
    protected $_customerSession;

    public function __construct(
        Template\Context $context,
        \Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderCollectionFactory,
        \Magento\Sales\Api\OrderRepositoryInterface $orderRepository,
        \Magento\Customer\Model\Session $customerSession,
        array $data = []
    ) {
        $this->_orderCollectionFactory = $orderCollectionFactory;
        $this->orderRepository = $orderRepository;
        $this->_customerSession = $customerSession;
        parent::__construct($context, $data);
    }

    public function getLoggedinCustomerId() 
    {
        if ($this->_customerSession->isLoggedIn()) {
            return $this->_customerSession->getId();
        }
        return false;
    }

    public function getOrderList($cust_id)
    {
        $order_collection = $this->_orderCollectionFactory->create();
        $order_collection->addFieldToFilter('customer_id', $cust_id);
        $order_collection->addAttributeToSelect('*');

        return $order_collection;
    }

    public function getOrderCount($cust_id)
    {
        $order_collection = $this->getOrderList($cust_id);
        return count($order_collection->getData());
    }

    public function getOrderItems($order_id)
    {
        return $this->orderRepository->get($order_id);
    }
}

app/code/VendoreName/ModuleName/view/frontend/templates

orderlist.phtml

//echo "<pre>";
$cust_id = $block->getLoggedinCustomerId();

$order_data = $block->getOrderList($cust_id);

//print_r($block->getOrderList($block->getLoggedinCustomerId())->getData()) ;

echo "<table border='1'><tr><th>Order ID</th><th>Order Items</th></tr>";
foreach ($order_data as $order_key => $order_value) {
    echo "<tr>";
    $order_id = $order_value->getIncrementId();
    echo "<td>".$order_id."</td>";
    echo "<td>";
    $order_items = $block->getOrderItems($order_id);
    if (!empty($order_items)) {
        foreach ($order_items->getAllVisibleItems() as $key_items => $value_items) {
            echo $value_items->getName()."<br/>";
        }
    } else {
        echo "No Items Found";
    }

    echo "</tr>";
}
echo "</table>";

You can add this to your layout where you want to show order items list.

<block class="VendoreName\ModuleName\Block\OrderList" name="customer_order_items" template="VendoreName_ModuleName::orderlist.phtml" cacheable="false"/>

I Hope This Helps You.

9
  • It looks like $block->getOrderItems($order_id); needs to send the entity id, rather than the order id to the function - I changed that and this then works well.
    – RichardB
    Jun 10, 2020 at 16:49
  • @Msquare how to get order count here of the logged in customer
    – Pramod
    Aug 10, 2021 at 15:29
  • @Pramod I added getOrderCount() function which return order count of particular customer.
    – Msquare
    Aug 11, 2021 at 4:07
  • this line :- return count($order_collection->getData()); in getOrderCount($cust_id) function throws error which says ParseError: syntax error, unexpected 'return' (T_RETURN)
    – Pramod
    Aug 11, 2021 at 6:56
  • @Pramod sorry it's a small mistake. I solve it now.
    – Msquare
    Aug 11, 2021 at 8:52
0

Try this code :

public function getOrders($customerId)
{

    if (!$this->orders) {
       $this->orders = $this->_orderCollectionFactory->create()
    ->addFieldToFilter('customer_id', [
        'eq' => $customerId
    ])
    ->setOrder('created_at', 'desc');
    }
    return $this->orders;
}
2
  • it displays an error on front-end : Invalid argument supplied for foreach(). I added if(is_array($orders) || is_object($orders)) before the foreach but now it doesn't display sth new
    – krisi
    Jun 8, 2018 at 11:20
  • So the problem is caused because i am passing something to foreach loop that is not an array
    – krisi
    Jun 8, 2018 at 11:26

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.