Magento 2 : load order by id in customer account order view

  • In the customer account order view page, I added a Block and an associated phtml file. Inside this phtml, I would like to load the order to access some information.

    NB: the block is added dynamically and not using XML

    I tried in my block :

    protected $_order;
    
    public function __construct(
            \Magento\Framework\View\Element\Template\Context $context,
            \Magento\Sales\Api\Data\OrderInterface $order
            )
    {
        $this->_order = $order;
        parent::__construct($context);
    }
    

    and in my pthml :

     $order = $block->_order->load($data['order_id']);
    

    but it results in an error.

    If someone could give me a hand, please?

  • Try following way:

    protected $orderRepository;
    
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Sales\Api\OrderRepositoryInterface $orderRepository,
        array $data = []
    ){
        $this->orderRepository = $orderRepository;
        parent::__construct($context, $data);
    }
    
    public function getOrder($id)
    {
        return $this->orderRepository->get($id);
    }
    

    From phtml

    $order = $block->getOrder($data['order_id']);
    

    It show an error that id is undefined

  • Declare \Magento\Sales\Api\OrderRepositoryInterface in construct of your class.

    Try following snippet:

    protected $orderRepository;
    
    public function __construct(
        \Magento\Sales\Api\OrderRepositoryInterface $orderRepository
    ){
        $this->orderRepository = $orderRepository;
    }
    

    Then you can do following:

    $order = $this->orderRepository->get($orderId);
    $orderIncrementId = $order->getIncrementId(); // To get order incremental id
    

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM