How to get customer_id in block and pass data to phtml file and also pass custom data from our module as grid. Here I'm getting null value when i was get customer_id in block file.
1 Answer
Try below code to get customer Id or Other customer data from block to template(phtml) file
app/code/YourCompanyName/YourModuleName/Block/YourCustomBlock.php
<?php
namespace YourCompanyName\YourModuleName\Block;
class YourCustomBlock extends \Magento\Framework\View\Element\Template
{
protected $_customerSession;
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Customer\Model\SessionFactory $customerSession,
array $data = []
) {
$this->_customerSession = $customerSession->create();
parent::__construct($context, $data);
}
public function getLoggedinCustomerId() {
if ($this->_customerSession->isLoggedIn()) {
return $this->_customerSession->getId();
}
return false;
}
public function getCustomerData() {
if ($this->_customerSession->isLoggedIn()) {
return $this->_customerSession->getCustomerData();
}
return false;
}
}
Now, we can use the functions in our view (.phtml) file as follows.
<?php
$customerId = $block->getLoggedinCustomerId();
echo 'Customer Id: ' . $customerId;
$customerData = $block->getCustomerData();
if($customerData) {
echo 'Customer Id: ' . $customerData->getId() . '<br/>';
echo 'Customer Name: ' . $customerData->getName() . '<br/>';
echo 'Customer Email: ' . $customerData->getEmail() . '<br/>';
echo 'Customer Group Id: ' . $customerData->getGroupId() . '<br/>';
}
You can also get customer Id directly in your template(phtml) file using below code
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $objectManager->create('Magento\Customer\Model\Session');
if ($customerSession->isLoggedIn()) {
echo 'Customer Id: ' . $customerSession->getCustomer()->getId() . '<br/>';
echo 'Customer Name: ' . $customerSession->getCustomer()->getName() . '<br/>';
echo 'Customer Email: ' . $customerSession->getCustomer()->getEmail() . '<br/>';
echo 'Customer Group Id: ' . $customerSession->getCustomer()->getGroupId() . '<br/>';
}
?>
NOTE: You only get customer id if customer logged in and customer session initialized
Hope that above code help you. If need any further help Let me know..!
-
I have created a grid by using uicomponent and i cannot know how to use it inside customer edit tab in magento2. Commented Nov 26, 2019 at 6:55