Override Customer Name Widget in Magento 2

0
3680
Override Customer Name Widget in Magento 2
Override Customer Name Widget in Magento 2

When designing a new theme for Magento 2, you might want to change the customer name widget. I will show you how to override customer name widget in Magento 2 in this article.

Override Customer Name Widget in Magento 2

The customer name widget is the widget the shown on customer account create form. By default, it shows input fields for first name and last name.

Create Account Name Widget in Magento 2
Create Account Name Widget in Magento 2

There are many techniques to override a widget; however, in my experiences, using plugin is the best way to achieve this without much effort to edit.

Let’s do this!

First, we add a new plugin in app/code/VENDOR/MODULE/etc/di.xml.

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

    <type name="Magento\Customer\Block\Widget\Name">
        <plugin name="vendor_module_plugin_widget_name" type="Vendor\Module\Plugin\Customer\Block\Widget\Name" />
    </type>

</config>

Then create a plugin class to handle that app/code/Vendor/Module/Plugin/Customer/Block/Widget/Name.php

<?php

namespace Vendor\Module\Plugin\Customer\Block\Widget;
class Name
{
    public function after_construct(\Magento\Customer\Block\Widget\Name $result)
    {
        $result->setTemplate('Vendor_Module::widget/name.phtml');
        return $result;
    }
}

Lastly, copy this file vendor/magento/module-customer/view/frontend/templates/widget/name.phtml into app/code/Vendor/Module/view/frontend/templates/widget/name.phtml.

Not forget to execute this command to rebuild the DI.

$ bin/magento setup:di:compile

Conclusion

It’s all done. As you can see, it is very simple to override customer name widget in Magento 2. The plugin technique is pretty useful and easy to implement.

References:

Have fun ~