Magento 2.1 – Call Custom PHTML on Success Page Without Override

magento-2.1magento2

In Magento 2 I want to call my custom phtml file order success page, but without overriding block. Is there any way to achieve this ?

I don't want to edit Magento success.phtml as I am creating module.

Any help will appreciated

Thanks.

Best Answer

You can use any of Magento's layout file in your module to insert your custom block. In your case you need to use checkout_onepage_success.xml layout file in your custom module which will be active when a customer is on order success page. In the layout file you need to specify where you want to add your custom template using referenceContainer or referenceBlock.

For you I've created a simple module and tested it which works fine.

registration.php

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Amit_Orderpage',
    __DIR__
);

composer.json

{
  "name": "amit/orderpage-module",
  "description": "Simple Magento 2 module that adds a new template on order success page.",
  "type": "magento2-module",
  "version": "1.0.0",
  "license": [
    "OSL-3.0",
    "AFL-3.0"
  ],
  "require": {
    "php": "~5.5.0|~5.6.0|~7.0.0",
    "magento/framework": "~100.0"
  },
  "autoload": {
    "files": [ "registration.php" ],
    "psr-4": {
      "Amit\\Orderpage\\": ""
    }
  }
}

etc/module.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Amit_Orderpage" setup_version="2.0.0"/>
</config>

Block/Success.php

<?php
namespace Amit\Orderpage\Block;
class Success  extends \Magento\Framework\View\Element\Template
{
    public function getSomething()
    {
        return 'returned something from custom block.';
    }
}

view/frontend/layout/checkout_onepage_success.xml

<?xml version="1.0"?>
<body>
    <referenceContainer name="order.success.additional.info">
        <block class="Amit\Orderpage\Block\Success"
               name="amit.order.success"
               template="Amit_Orderpage::order/success.phtml"
               after="-">
        </block>
    </referenceContainer>
</body>

Specify before or after tag to specify where you want to add your template before or after order.success.additional.info container. Here after="-" will add your your template to order.success.additional.info container after all other containers present in the same section.

view/frontend/templates/order/success.phtml

<?php /* @var $block \Amit\Orderpage\Block\Success */?>
<?php echo __('Custom template file content.'); ?>
<?php echo $block->getSomething(); ?>
Related Topic