Question

in the success.phtml file I currently have a direct use of the object manager, which I am now reading is not best practice. I was wondering how to make a constructor to replace the following code in accordance with Magento best practices.

    $oid = $this->getOrderId();
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $order = $objectManager->create('Magento\Sales\Model\Order')->load($oid);
Was it helpful?

Solution

The git repository order success page analytics repo may show you what you are after.

I wrote this repo to answer a question on Magento Stack Exchange that asked to put analytics on the order success page..

Now, in terms on best practice, this repo uses ViewModel and this is what Vinai Kopp did advise us to use back in March 2018 in a Magento 2 training.

OTHER TIPS

Create a new module.

In this module create a Block Class which extends

Magento\Checkout\Block\Success

add this Magento\Sales\Model\Order as an injection to your block constructor.

create a function for the data you need.

Add a di.xml and in this add a preference:

<preference for="Magento\Checkout\Block\Success" type="Vendor\ModuleName\Block\YourFileName"/>

Create a layout file in Vendor/ModuleName/view/frontend/layout/checkout_onepage_success.xml with this content.

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
    <referenceContainer name="content">
        <block class="Magento\Checkout\Block\Onepage\Success" name="checkout.success" template="Vendor_ModuleName::success.phtml" cacheable="false"/>
    </referenceContainer>
</body>
</page>

Copy the file [magenot_root]/vendor/magento/module-checkout/view/frontend/templates/success.phtml to your module/frontend/templates/

and edit this success.phtml as you desire.

Hope this helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top