0

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. enter image description here

In frontend website menu. enter image description here

Any help on this?

7
  • Please share your .phtml file code, and if possible, please share the whole code of the block, .phtml, and layout.
    – Msquare
    Feb 23 at 7:27
  • @Msquare Updated my thread with block and .phtml code
    – Bojjaiah
    Feb 23 at 9:20
  • What will that Customers link show or where it should redirect for logged-in customers? Feb 23 at 9:31
  • @LokeshNaik When we click on the customer link it will redirect to salesrep/index/account.
    – Bojjaiah
    Feb 23 at 11:25
  • Is salesrep/index/account is from your custom module or 3rd party module? If it is from your module can you post the controller and layout code? Feb 23 at 13:09

2 Answers 2

1
+50

It is not recommended to get customer session in places which can be cached. Since the page you are working with is a cms page, it would be cached and once it's cached the cache server (fastly or varnish)/ magento (magento's build-in cache) will directly serve the page's cached html without going into your block to get session values. At best, it would show stale or no values and at worst it may show data of previous customer as well.

The way to do it would be populate your data in customer section, retrieve it on page load the populate it on the page. You can read up more about customer sections in this post - Magento 2: how do customer sections / sections.xml work?

1
  • I will check, and let you know
    – Bojjaiah
    Feb 23 at 9:21
1

Category page will always be cached. Also, block directives in the CMS does not provide as many options as layout block. You cannot disable cache inside a CMS block. If you want to show dynamic content for each customer on category page then create a custom layout handle which disables cache conditionally for specific category and insert it to the current layout using an observer.

Refer below code

  1. Create a custom layout handle

app/code/ABCSolutions/Customer/view/frontend/layout/catalog_category_view_customers.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="content">
            <block class="ABCSolutions\Customer\Block\Accounts" name="sales_rep_accounts" template="ABCSolutions_Customer::accounts.phtml" cacheable="false" />
        </referenceContainer>
    </body>
</page>
  1. Declare a custom observer for event load_layout_before

app/code/ABCSolutions/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="layout_load_before">
        <observer name="abc_solutions_addcustomershandle"
                  instance="ABCSolutions\Customer\Observer\AddCustomersHandle" />
    </event>
</config>
  1. Add custom handle to the category layout using event

app/code/ABCSolutions/Customer/Observer/AddCustomersHandle.php

<?php

namespace ABCSolutions\Customer\Observer;

use Magento\Framework\Event\Observer as EventObserver;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Registry;

/**
 *  AddCustomersHandle
 */
class AddCustomersHandle implements ObserverInterface
{    
    /**
     * @var Registry
     */
    private $registry;
    
    /**
     * @param Registry $registry
     */
    public function __construct(Registry $registry)
    {
        $this->registry = $registry;
    }
    
    /**
     * @param EventObserver $observer
     */
    public function execute(EventObserver $observer)
    {
        $action = $observer->getData('full_action_name');
        if ($action != 'catalog_category_view')
            return $this;

        $category = $this->registry->registry('current_category');
        if (!$category)
            return $this;

        if ($category->getName() == 'Customers') { // add your conditions
            $layout = $observer->getData('layout');
            $layout->getUpdate()->addHandle('catalog_category_view_customers');
       }

        return $this;
    }
}
2
  • Lokesh, I already have this code to redirect the page when we click on any category. This is not my question. I cannot access the customer session in the custom module when we redirect the page using the above concept.
    – Bojjaiah
    Feb 26 at 9:10
  • @Bojjaiah Check my edited answer above. Feb 26 at 12:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.