0

I tried to get the customer session in my custom module, but it is getting null always when using <update handle="customer_update"/> in the layout file.

If I comment <update handle="customer_update"/> the customer session is getting.

And My code is below.

Block file

<?php

namespace Learning\CustomerAccLink\Block;

use Magento\Customer\Model\Session as Session;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\View\Element\Template\Context;

class CustomerLink extends \Magento\Framework\View\Element\Template
{

    /**
     * Session object.
     *
     * @var Session
     */
    private $customerSession;

    /**
     *
     * Object initialization.
     *
     * @param Context $context
     * @param Session $session
     * @param array $data
     */
    public function __construct(
        Context $context,
        Session $session,
        array $data = []
    ){
        $this->customerSession = $session;
        parent::__construct($context, $data);
    }

    /**
     * Get Customer Group ID
     *
     * @return int
     * @throws LocalizedException
     * @throws NoSuchEntityException
     */
    public function getCustomerGPID(): int
    {
        return $this->customerSession->getCustomer()->getGroupId();
        /*try {

        }catch (LocalizedException|NoSuchEntityException $ex){
            return 0;
        }*/
    }

}

Controller file

  <?php

namespace Learning\CustomerAccLink\Controller\Index;

use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;

class Index extends \Magento\Framework\App\Action\Action
{

    /**
     * @var PageFactory
     */
    protected $resultPageFactory;


    /**
     * @param Context $context
     * @param PageFactory $resultPageFactory
     */
    public function __construct(
        Context $context,
        PageFactory $resultPageFactory
    ) {
        $this->resultPageFactory = $resultPageFactory;
        parent::__construct($context);
    }

    /**
     * Default customer account page
     *
     * @return Page
     */
    public function execute()
    {
        //echo "Hello";
        return $this->resultPageFactory->create();
    }

}

routes.xml file

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="standard">
        <route id="learning" frontName="learning">
            <module name="Learning_CustomerAccLink" />
        </route>
    </router>
</config>

module.xml file

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Learning_CustomerAccLink" >
    </module>
</config>

customer_account.xml file

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="2columns-left"
      xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"
      label="Customer My Account (All Pages)" design_abstraction="custom">
    <body>
        <attribute name="class" value="account"/>
        <referenceContainer name="customer_account_navigation">
            <block class="Magento\Framework\View\Element\Html\Link\Current"
                   name="customer-account-navigation-custom-link" after="-">
                <arguments>
                    <argument name="label" xsi:type="string" translate="true">Customer Link</argument>
                    <argument name="path" xsi:type="string">learning</argument>
                </arguments>
            </block>
        </referenceContainer>
    </body>
</page>

learning_index_index.xml file

<?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">
   <!-- <update handle="customer_account"/>-->
    <body>
        <referenceContainer name="content">
            <block class="Learning\CustomerAccLink\Block\CustomerLink" name="custom_customer_link" template="customerLink.phtml" />
        </referenceContainer>
        <referenceBlock name="root">
            <action method="setHeaderTitle">
                <argument translate="true" name="title" xsi:type="string">Customer Link | Learning</argument>
            </action>
        </referenceBlock>
    </body>
</page>

customerLink.xml file

<?php

/** @var $block Learning\CustomerAccLink\Block\CustomerLink */

?>


<?php  echo $block->getCustomerGPID(); ?>

registration.php file

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Learning_CustomerAccLink',
    __DIR__
);

Was there I missed any?

Thanks,

0

2 Answers 2

3

Add cacheable="false" in your xml

<referenceContainer name="content">
     <block class="Vendor\Modulename\Block\Customer" name="customer.session.data" template="Vendor_Modulename::customertab.phtml" cacheable="false" />
 </referenceContainer>

and get customer data :

/**
 * @var \Magento\Customer\Model\Session
 */
protected $_customerSession;

public function __construct(Template\Context $context,
        \Magento\Framework\App\Request\Http $request,
        \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository,
        \Magento\Customer\Model\SessionFactory $customerSession
    ) 
{
    $this->request = $request;
    $this->customerRepository = $customerRepository;
    $this->_customerSession = $customerSession;
    parent::__construct($context);
}

public function getCustomerId(){
    $customer = $this->_customerSession->create();
    var_dump($customer->getCustomer()->getId());
}
12
  • Thank you for the answer. Without cacheable="false" can't get? Any reason?
    – Bojjaiah
    Commented Jul 20, 2022 at 13:02
  • Another way to get customer id with out cachable = "false" is httpContext Commented Jul 20, 2022 at 13:08
  • it is depend on which page. Commented Jul 20, 2022 at 13:08
  • Ok, All other modules it is working. When using <update handle="customer_account"/> it is not working.
    – Bojjaiah
    Commented Jul 20, 2022 at 13:12
  • 1
    mageclues.com/blog/… Commented Jul 20, 2022 at 13:21
0

If you cannot get customer id at your block class when your page hits full page cache. You have to pass the customer id as an HTTP context variable. Create a plugin class on Magento\Framework\App\Action\AbstractAction.

app/code/VendoreName/ModuleName/etc

di.xml

<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">

    <type name="Magento\Framework\App\Action\AbstractAction">
        <plugin name="get_customr_id_full_page"  disabled="false" sortOrder="20" type="VendoreName\ModuleName\Plugin\Framework\App\Action\AbstractAction"/>
    </type>

    </type>
</config>

On plugin pass current customer id as http context variable:

app/code/VendoreName/ModuleName/Plugin/Framework/App/Action

AbstractAction.php

<?php

declare(strict_types=1);

namespace VendoreName\ModuleName\Plugin\Framework\App\Action;

use Magento\Customer\Model\Context as CustomerContext;
use Magento\Framework\Exception\NoSuchEntityException;

class AbstractAction
{

    /**
     * @var \Magento\Customer\Api\CustomerRepositoryInterface
     */
    private $customerRepository;

    /**
     * @var \Magento\Customer\Model\Session
     */
    private $customerSession;

    /**
     * @var \Magento\Framework\App\Http\Context
     */
    private $httpContext;

    /**
     * @param \Magento\Customer\Model\Session $customerSession
     * @param \Magento\Framework\App\Http\Context $httpContext
     * @param \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository
     */
    public function __construct(
        \Magento\Customer\Model\Session $customerSession,
        \Magento\Framework\App\Http\Context $httpContext,
        \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository
    ) {
        $this->customerSession = $customerSession;
        $this->httpContext = $httpContext;
        $this->customerRepository = $customerRepository;
    }

    /**
     * @inheritdoc
     */
    public function aroundDispatch(
        \Magento\Framework\App\ActionInterface $subject,
        callable $proceed,
        \Magento\Framework\App\RequestInterface $request
    ) {

        $customerId = $this->customerSession->getCustomerId();
        $this->httpContext->setValue(
            'current_cust_id',
            $customerId,
            0
        );

        return $proceed($request);
    }
}

After that Inject, \Magento\Framework\App\Http\Context on your block class and get this customer id value by $this->httpContext->getValue('current_cust_id')

Note: A single cacheable="false" will disable Full Page Caching for the whole page, making the pages sourcing from that layout file extremely slow! Click here for more

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.