
Magento 2.x – Add a custom customer attribute on his dashboard page.
In addition of a previous comment where we added a new attribute to the customer (https://www.offset101.com/magento-2-x-add-custom-attribute-customer-model-show-admin-panel/ ), here, we are going to add this attribute to the dashboard page of the customer.
At first, we need to know that all fields are rendered in the customer-module, so you will need to override the following file
1 |
../vendor/magento/module-customer/view/frontend/templates/form/edit.phtml |
to the corresponding one on your theme (or module).
Afterwards, and keeping the best Magento practice, we will need to override with a preference, the following Magento Block:
1 |
<span class="pln">\Custom\B</span><span class="kwd">lock</span><span class="pln">\Magento\Customer\Form</span><span class="pun">;</span> |
To do so, let’s perform the following steps, and create the following files:
- /Company/Custom/Block/Magento/Customer/Form/Edit.php
123456789101112<?phpnamespace Compony\Custom\Block\Magento\Customer\Form;class Edit extends \Magento\Customer\Block\Form\Edit{public function getCustomField(){return $this->customerSession->getCustomer()->getCustomField();}} - /Company/Custom/etc/di.xml
1234<?xml version="1.0"?><config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"><preference for="Magento\Customer\Block\Form\Edit" type="Company\Custom\Block\Magento\Customer\Form\Edit" /></config>
After adding it, you will be able to add your custom field, in the edit.phtml overrided before, with the following line of code:
1 |
<input type="text" class="input-text" value="<?php echo $block->getCustomField();?>" name="custom_field" id="custom_field" data-input="custom_field" /> |
Remember to clean cache, and do a setup upgrade.
Happy Coding!