How to Override a phtml File Using a Custom Module in Magento 2
It is well known that customizing the core Magento 2 functionality is a bad coding practice. Once you upgrade the Magento version, your efforts are in vain. Hence, it is advisable to override a function, class or file, as per the requirement.
Here, I’ll show you how to override a phtml file using a custom module in Magento 2.
There are two methods to do so as mentioned below:
Methods to Override a phtml file using a custom module in Magento 2:
- Create file registration.php at app/code/Vendor/Extension/ folder
123456<?php\Magento\Framework\Component\ComponentRegistrar::register(\Magento\Framework\Component\ComponentRegistrar::MODULE,'Vendor_Extension',__DIR__); - Create module.xml file at app/code/Vendor/Extension/etc/ folder
123456<?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="Vendor_Extension" setup_version="1.0.0"></module></config>
- Create file customer_account_create.xml at app/code/Vendor/Extension/view/frontend/layout/ folder
12345678910<?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_form_register"><action method="setTemplate"><argument name="template" xsi:type="string">Vendor_Extension::form/register.phtml</argument></action></referenceBlock></body></page>
now you need to create register.phtml at location app/code/Vendor/Extension/view/frontend/templates/form/
That’s it.
The above example shows how to override a phtml file for customer register page. The default functionality to show out of stock is overridden to display an image.
Follow any of the above method suitable to you.
Please share your doubts on the topic in the Comments section below. I’d be happy to help.
Thank you.
Sanjay Jethva
Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe.
His passion for Magento 2 and Shopify solutions has made him a trusted source for businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.
2 Comments
Hello,
Parse error: syntax error, unexpected ‘ class’ (T_STRING) in plugin class Name Any solution
Hey,
Such error occur when there is a mistake of either semicolon or PHP tag.
Thanks.