Magento 2 Get customer ID from session in a block class
It's working copy. You can compare with your block class. Here I use Form as block class
namespace Vendor\Module\Block;
class Form extends \Magento\Framework\View\Element\Template
{
protected $customerSession;
/**
* Construct
*
* @param \Magento\Framework\View\Element\Template\Context $context
* @param \Magento\Customer\Model\Session $customerSession
* @param array $data
*/
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Customer\Model\Session $customerSession,
array $data = []
) {
parent::__construct($context, $data);
$this->customerSession = $customerSession;
}
public function _prepareLayout()
{
var_dump($this->customerSession->getCustomer()->getId());
exit();
return parent::_prepareLayout();
}
}
When You define block which use session You have to disable cache for it.
<block class="Vendor\Module\Block\Index" name="Name"
template="Vendor_Module::template/path.phtml" cacheable="false">
</block>
You need to inject \Magento\Customer\Model\Session $customerSession,
class to get customer ID from customer session.
protected $_customerSession;
public function __construct(
...
\Magento\Customer\Model\Session $customerSession,
...
) {
...
$this->_customerSession = $customerSession;
...
}
public function getCustomer()
{
echo $this->_customerSession->getCustomer()->getId(); //Print current customer ID
$customerData = $this->_customerSession->getCustomer();
print_r($customerData->getData()); //Print current Customer Data
}
NOTE: You only get customer id if customer logged in and customer session initialized