skip to Main Content

If we need to get current customer session in a block, cacheable must be set to false in the layout xml. I am using MagentoCustomerModelSessionFactory $customerSession in my block but it is not working without cacheable false. Can someone tell me a recommended way to solve this problem.

2

Answers


  1. Session is cached in blocks by default. However you can use a cacheable = false to use a Session in block but is not recommended.

    I recommend to use a Registry to store/get information in blocks. If you need specific info from Session you can set this info in a Registry from Controller of your Block.

    Here is some info: https://meetanshi.com/blog/use-registry-in-magento-2/

    Good Luck !

    Login or Signup to reply.
  2. Can you please check this? It Might be help you.

    namespace VendorModuleBlock;
    
    
    class Form extends MagentoFrameworkViewElementTemplate
    {
        protected $customerSession;
    
        /**
         * Construct
         *
         * @param MagentoFrameworkViewElementTemplateContext $context
         * @param MagentoCustomerModelSession $customerSession
         * @param array $data
         */
        public function __construct(
            MagentoFrameworkViewElementTemplateContext $context,
            MagentoCustomerModelSession $customerSession,
            array $data = []
        ) {
            parent::__construct($context, $data);
    
            $this->customerSession = $customerSession;
        }
    
        public function _prepareLayout()
        {
    
            var_dump($this->customerSession->getCustomer()->getId());
            exit();
            return parent::_prepareLayout();
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search