How to update the Document and Page Title from a Controller in Magento 2

How to update page title magento 2

Sometimes you need to change on the fly the Page and/or the Document Title for certain view in Magento 2 from a Controller or a Block class. To accomplish this, you also need to have the knowledge on How to Extend a Controller or Block in Magento 2,
but for now, let’s keep it simple and focus only in the Page Title and Document Title change.

We present you a real example compatible with Magento 2.1.x and 2.2.x extending the Order View controller to show another Order Id from an external resource.

use Magento\Sales\Controller\Order\View as MagentoView;

class View extends MagentoView {
    * Order view page
    * @return ResultInterface
    public function execute()
        /** @var \Magento\Framework\View\Result\Page $resultPage */
        $resultPage = $this->resultPageFactory->create();

        // Get OrderId by request
        $orderId = $this->getRequest()->getParam( 'order_id' );

        if($orderId) {
            // Load Order by OrderId
            $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
            $order = $objectManager->create('\Magento\Sales\Model\Order')->load($orderId);

            // Update Tab and Page title components
            $resultPage->getLayout()->getBlock( 'page.main.title' )->setPageTitle( "Order #".$order->getExtOrderId() );
            $resultPage->getConfig()->getTitle()->set("Order #".$order->getExtOrderId() );

        return $resultPage;

The important lines of code here are these below:

    $resultPage->getLayout()->getBlock( 'page.main.title' )->setPageTitle( "Order #".$order->getExtOrderId() );
    $resultPage->getConfig()->getTitle()->set("Order #".$order->getExtOrderId() );

The first one is to update the Page Title and the second to update Tab Title or Document Title.

Please let us know if you have any questions or leave us your comment if you have a better way to do this.

We believe in Our Magento Ecosystem!

Leave a Reply

Your email address will not be published. Required fields are marked *