We would like to a custom text field in my account dashboard account infomation section using custom module in magento2
Please find the screenshot below:
Thanks
We would like to a custom text field in my account dashboard account infomation section using custom module in magento2
Please find the screenshot below:
Thanks
Create two attributes
Create two fields this template
Now register event listener.
VendorName/Customer/etc/frontend/events.xml
<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="customer_account_edited">
<observer name="vendorname_customer_account_edited" instance="VendorName\Customer\Observer\CustomerAccountEdited"/>
</event>
</config>
VendorName/Customer/Observer/CustomerAccountEdited.php
<?php
namespace VendorName\Customer\Observer;
use Magento\Framework\Event\Observer as EventObserver;
use Magento\Framework\Event\ObserverInterface;
class CustomerAccountEdited implements ObserverInterface
{
/**
* @var \Magento\Customer\Api\CustomerRepositoryInterface
*/
protected $customerRepository;
/**
* @var \Magento\Framework\App\Request\Http
*/
protected $request;
/**
* @var \Magento\Store\Model\StoreManagerInterface
*/
protected $storeManager;
/**
* @var \Psr\Log\LoggerInterface
*/
protected $logger;
/**
* CustomerAccountEdited constructor.
*
* @param \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository
* @param \Magento\Framework\App\Request\Http $request
* @param \Magento\Store\Model\StoreManagerInterface $storeManager
* @param \Psr\Log\LoggerInterface $logger
*/
public function __construct(
\Magento\Customer\Api\CustomerRepositoryInterface $customerRepository,
\Magento\Framework\App\Request\Http $request,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Psr\Log\LoggerInterface $logger
) {
$this->customerRepository = $customerRepository;
$this->request = $request;
$this->storeManager = $storeManager;
$this->logger = $logger;
}
/**
* @param EventObserver $observer
* @return $this
*/
public function execute(EventObserver $observer)
{
$email = $observer->getEvent()->getEmail();
$customerData = $this->request->getPostValue();
if(isset($customerData['phone_number']) && $customerData['phone_number']) {
try {
$customerObj = $this->customerRepository->get($email, $this->storeManager->getStore()->getWebsiteId());
$customerObj->setCustomAttribute('mobile', $customerData['mobile_country_code'].$customerData['phone_number']);
$this->customerRepository->save($customerObj);
} catch (\Exception $e) {
$this->logger->critical($e->getMessage());
}
}
}
}
[Update]
For geting value from template use class method or create helper method.
Ex:
public function getCustomerMobile($customer)
{
$mobile = $customer->getCustomAttribute('mobile');
if(!$mobile) {
return '';
}
$mobile = $mobile->getValue();
return $mobile;
}