I'm not able to access the customer session in my custom module. However, when I'm navigating my custom action to salesrep/index/account I'm able to get the customer session. But when I'm navigating my custom module via category click not able to access it.
Here is my code. Controller Code
<?php
namespace ABCSolutions\Customer\Controller\Index;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\ResponseInterface;
use Magento\Framework\View\Result\PageFactory;
use Psr\Log\LoggerInterface as Logger;
class Accounts extends \Magento\Framework\App\Action\Action
{
/**
* @var PageFactory
*/
protected $resultPageFactory;
/**
* Logger.
*
* @var Logger
*/
protected $logger;
/**
* Core store config
* @var ScopeConfigInterface
*/
protected $_scopeConfig;
/**
* @param Context $context
* @param PageFactory $pageFactory
* @param ScopeConfigInterface $scopeConfigInterface
* @param Logger $loggerInterface
*/
public function __construct(
Context $context,
PageFactory $pageFactory,
ScopeConfigInterface $scopeConfigInterface,
Logger $loggerInterface,
){
$this->resultPageFactory = $pageFactory;
$this->_scopeConfig = $scopeConfigInterface;
$this->logger = $loggerInterface;
parent::__construct($context);
}
/**
* @return ResponseInterface|\Magento\Framework\Controller\ResultInterface|\Magento\Framework\View\Result\Page
*/
public function execute()
{
$page = $this->resultPageFactory->create();
$page->getConfig()->getTitle()->set(__('Customers'));
return $page;
}
}
Block Code:
<?php
namespace ABCSolutions\Customer\Block;
use Magento\Framework\View\Element\Template;
use Magento\Framework\View\Element\Template\Context;
use Magento\Customer\Model\Session as CustomerSession;
class Accounts extends Template
{
/**
* @var CustomerSession
*/
protected $customerSession;
/**
* @param Context $context
* @param CustomerSession $customerSession
*/
public function __construct(
Context $context,
CustomerSession $customerSession
){
$this->customerSession = $customerSession;
parent::__construct($context);
}
public function getCustomerId()
{
if ($this->customerSession->isLoggedIn()) {
return $this->customerSession->getCustomer()->getId();
}
return 0;
}
}
Layout code
<referenceContainer name="content">
<block class="ABCSolutions\Customer\Block\Accounts" name="sales_rep_accounts" template="ABCSolutions_Customer::accounts.phtml" cacheable="false" />
</referenceContainer>
Phtml code:
<?php /** @var $block ABCSolutions\Customer\Block\Accounts */ ?>
$customerId = $block->getCustomerId();
Static Block:
{{block class="ABCSolutions\Customer\Block\Accounts" template="ABCSolutions_Customer::accounts.phtml"}}
And the Category:
For this category there are no products, So when we click on this the custom module will show.

Any help on this?

blockand.phtmlcode – Bojjaiah Feb 23 '24 at 09:20