I am trying to display a customer's name after login (M2 version)
Question: How do I display a customer's name after login in Magento 2?
I see here it is a little more difficult: Customer name is not display after login in magento 2
I am trying to display a customer's name after login (M2 version)
Question: How do I display a customer's name after login in Magento 2?
I see here it is a little more difficult: Customer name is not display after login in magento 2
I customised to login logout and it is working well but I need customer name two thing I used for customised
1) link.php
2) authorization.phtml
I have such code in link.php:
if (false != $this->getTemplate()) {
return parent::_toHtml();
}
return '<div><a ' . $this->getLinkAttributes() . ' >' . $this->escapeHtml($this->getLabel()) . '</a></div>';
}
There are two way
Using object manager into your phtml file:
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $objectManager->create('Magento\Customer\Model\Session');
if ($customerSession->isLoggedIn()) {
$customerSession->getCustomerId(); // get Customer Id
$customerSession->getCustomerGroupId();
$customerSession->getCustomer();
$customerSession->getCustomerData();
echo $customerSession->getCustomer()->getName(); // get Full Name
echo $customerSession->getCustomer()->getEmail(); // get Email
}
Construct customer session class into your relevant block and create a function to get Customer name. Then call your block function from your phtml file.
Use the below function in your helper file with Magento\Customer\Model\Session
to get session object in $customerSession
public function getLoggedinCustomerName(){
if($customerSession->getData('customer_id'))
{
$customer = $this->_customerRepositoryInterface->getById($customerSession->getData('customer_id'));
return $customer->getFirstname();
}
else
{
return "Guest";
}
}
and in use it in your PHTML file
<?php
$customerName = $helper->getLoggedinCustomerName();
?>
<a href="<?php echo $block->getUrl('customer/account/'); ?>">
<i class="fa fa-user" aria-hidden="true"></i>
<span class="label"><?php /* @escapeNotVerified */ echo 'Hello '. $customerName; ?></span>
</a>
Php Block --
$customer = $this->customerRepository->getById($this->customerSession->getCustomerId());
echo $block->getLayout()->createBlock('Magento\Customer\Block\Widget\Name')->setObject($customer)->toHtml()
Some case: Bug of Magento 2 when you turn on caches. You must reload customer sections when customer logged in. Check etc/sections.xml and customer-data.js you will know how to reload customer sections. Regards.
I will update related link later.