Magento 2 Payment Methods – How to Get Last Order ID in Payment Module Template

magento2payment-methods

I am creating a custom payment method module in magento2.

On order place redirecting to to my request controller from script. In request controller I have below code :

...
$resultPage = $this->_pageFactory->create();
$resultPage->addHandle('custom_request_index');
return $resultPage;
...

In xml file added template file form.phtml and it is loading on the page.

All are working but I am trying to get last order id in form.phtml file as below :

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$checkout_session = $objectManager->get('\Magento\Checkout\Model\Session');
$incrementId = $checkout_session->getLastRealOrderId();
echo $incrementId;

But above code returning nothing. But when I try to log same code in request controller then it returns correct order id.

I have also tried to add a function in block file to get order id in template file like $block->getLastOrder() but this function also returning nothing, while other functions in block file working properly.

Why this is happening? How to get last order id in form.phtml file?

Best Answer

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$checkout_session = $objectManager->get('Magento\Checkout\Model\Session');
$order = $checkout_session->getLastRealOrder();
$orderId= $order->getEntityId();
echo $order->getIncrementId();

It can help you There is a mistake in 2nd line

$checkout_session = $objectManager->get('Magento\Checkout\Model\Session');