Search code examples
phpmagento2

Magento 2: override .phtml file in a custome module


I am new to Magento 2 and I'm not quite understand its structure yet. I'm using its sample data to investigate code. I want to override a .phtml file by using a custome module. The file I want to override is:

vendor/magento/module-customer/view/frontend/templates/account/dashboard/info.phtml

So far, I create a file in this path:

src/app/code/NewModule/NewModuleTest/view/frontend/templates/customer/account/dashboard/info.phtml

I copy that original file to this and make some simple changes like add a tag, changing text. After that, I run command:

bin/magento setup:upgrade

bin/magento cache:clean

But nothing happen. I don't know if I'm missing anything. I also clear browser's cache. Please help me. Any ideas are appreciated. Thank you all!

P/s: I don't know if this is related, I install Magento by this repo on Github: Docker Magento


Solution

  • I figured out how to do this

    Identify files you want to override

    • Original template file:

    vendor/magento/module-customer/view/frontend/templates/account/dashboard/info.phtml

    • Original layout file:

    vendor/magento/module-customer/view/frontend/layout/customer_account_index.xml

    • Original block inside layout file (where this template is assigned to):
    <block class="Magento\Customer\Block\Account\Dashboard\Info" name="customer_account_dashboard_info" as="info" template="Magento_Customer::account/dashboard/info.phtml" cacheable="false">
        <container name="customer.account.dashboard.info.blocks" as="additional_blocks"/>
    </block>
    

    Override steps

    • Create a layout file with the same name with the original name:

    app/code/NewModule/NewModuleTest/view/frontend/layout/customer_account_index.xml

    • Put code with referenceBlock tag and original block’s ‘name’
    <?xml version="1.0"?>
    <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
        <body>
            <referenceBlock name="customer_account_dashboard_info" template="NewModule_NewModuleTest::customer/account/dashboard/info.phtml"/>
        </body>
    </page>
    
    • Create the template .phtml file: /app/code/NewModule/NewModuleTest/view/frontend/templates/customer/account/dashboard/info.phtml

    Then it's done!