2

i am trying to get customer id of a logged in customer but its does not seems to be working

in my block

<?php
namespace Vendor\Module\Block;
use Magento\Framework\View\Element\Template;
use Magento\Backend\Block\Template\Context;

class Rfq extends \Magento\Framework\View\Element\Template
{    
    protected $_customerSession;    
    public function __construct(Context $context,
        \Magento\Customer\Model\Session $customerSession,
 
        array $data = [])
    {
        parent::__construct($context, $data);
        $this->_customerSession = $customerSession;   
    }

            public function getCustomerId()
                    {
                         if($this->_customerSession->isLoggedIn()):
                              return $this->_customerSession->getCustomer()->getId();                        
                         endif;
                    }

            public function execute()
            {

                $this->_view->loadLayout();
                $this->_view->getLayout()->initMessages();
                $this->_view->renderLayout();
            }
        }

Now in phtml file

<?php
$customerId = $customer->getCustomerId();
?>

any suggestion or issue in code thankss

Update controller

<?php
namespace Vendor\Module\Controller\Index;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\View\Result\PageFactory;

class Customer extends \Magento\Framework\App\Action\Action
{
    protected $resultPageFactory;

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

        return $this->resultPageFactory->create();
        $this->_view->loadLayout(); 
        $this->_view->renderLayout(); 
    }


  
} 
 
4
  • 1
    with full page cache enabled you might have problems using session data, another option is to make an ajax call to get the customer id. A similar question and answers is here magento.stackexchange.com/questions/178423/…
    – paj
    Sep 4, 2020 at 13:00
  • please share your block file full code
    – Msquare
    Sep 7, 2020 at 9:59
  • ok done please check
    – Pramod
    Sep 7, 2020 at 10:03
  • please check updated answer and update me.
    – Msquare
    Sep 7, 2020 at 10:21

6 Answers 6

4

If you cannot customer id at your block class when your page hit at full page cache.

You have to pass the customer id as an HTTP context variable.

See https://devdocs.magento.com/guides/v2.3/extension-dev-guide/cache/page-caching/public-content.html#configure-page-variations

Create a plugin class on Magento\Framework\App\Action\AbstractAction.

<?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="add_customr_id_full_page"  disabled="false" sortOrder="20"
                type="Devamitbera\Module\Plugin\Framework\App\Action\AbstractAction"/>        
    </type>   

    </type>      
</config>

On plugin pass current customer id as http context variable:

<?php

declare(strict_types=1);

namespace Devamitbera\Module\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;

    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;
    }
    

    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')

2
  • exactly this is the only way thankss a lot
    – Pramod
    Sep 8, 2020 at 12:08
  • I wish this answer was slightly more detailed, it is not super clear how to actually use this in a custom module. Oh sweet lord I hate working with Magento, why is getting something so simple and commonly required as the customer ID so flipping convoluted ... Why can you get the customer group but not the ID?? 😑🔫
    – 00-BBB
    Mar 10, 2021 at 14:58
1

Your block code need to like this one:

public function getCustomerId()
{
     if($this->_customerSession->isLoggedIn()) {
          return $this->_customerSession->getCustomer()->getId();                        
     }
}

And in phtml you need to call like this one :

<?php $customerId = $block->getCustomerId(); ?>
8
  • will it work even when the cache is enabled?
    – Pramod
    Sep 7, 2020 at 6:54
  • Yes, you can try Sep 7, 2020 at 7:57
  • yes fpc issue is there it giving the same customer id even the customer has logged out
    – Pramod
    Sep 7, 2020 at 10:06
  • But according to code, it will not going into if, because the customer is not login. Sep 7, 2020 at 14:01
  • even though customer is logged in still not working
    – Pramod
    Sep 8, 2020 at 4:05
0

Your Code is perfect.I am assuming your block file call in your .xml file and in xml file call .phtml file.And you run below all commands like :-

remove your var/cache
remove your var/view_preprocessed
php bin/magento setup:di:compile
php bin/magento s:up
php bin/magento s:s:d -f
php bin/magento c:c
php bin/magento c:f

After you check your output.And Again not show your output check your log error share with me.

THANKS.

1
  • i have already tried
    – Pramod
    Sep 7, 2020 at 4:39
0

In Block file you need to change code as below

From:

<?php
$customerId = $customer->getCustomerId();
?>

To:

<?php
$customerId = $block->getCustomerId();
?>
1
  • this is not working
    – Pramod
    Sep 7, 2020 at 4:39
0

If customer is logged in then you can't get From Session Try this way

public function __construct(
    \Magento\Framework\App\Http\Context $customerContext,
    \Magento\Customer\Model\SessionFactory $customer
{
    $this->customer           = $customer;
    $this->customerContext        = $customerContext;
}

public function getCustomerID()
{
    $customerLoggedIn= $this->customerContext->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH);
    if($customerLoggedIn){
        $customerId = $this->customer->create()->getCustomer()->getId();
        return $customerId;
    }
}
0

Use this into you layout file where you add your block.

cacheable="false"

        <block class="VendoreName\ModuleName\Block\BlockName"
               name="block_index_edit"
               template="VendoreName_ModuleName::edit.phtml"
               cacheable="false" />

Update

Your Controller File

<?php
namespace Vendor\Module\Controller\Index;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\View\Result\PageFactory;

class Customer extends \Magento\Framework\App\Action\Action
{
    protected $resultPageFactory;

    public function __construct(
        Context $context,
        PageFactory $resultPageFactory
    ) {
        $this->resultPageFactory = $resultPageFactory;
        parent::__construct($context);
    }
    public function execute()
    {
        return $this->resultPageFactory->create();
        $this->_view->loadLayout(); 
        $this->_view->renderLayout(); 
    }
} 

Your Block File

<?php

namespace VendoreName\ModuleName\Block;

use Magento\Framework\View\Element\Template;

class Rfq extends Template
{
    protected $request;
    protected $sessionFactory;

    public function __construct(
        Template\Context $context,
        \Magento\Framework\App\Request\Http $request,
        \Magento\Customer\Model\SessionFactory $sessionFactory,
        array $data = []
    ) {
        parent::__construct($context, $data);
        $this->sessionFactory = $sessionFactory;
        $this->request = $request;
    }

    public function getCustomerId()
    {
        // get customer id here
        $customerSession = $this->sessionFactory->create();
        return $customerSession->getCustomer()->getId();
    }

}

Your phtml file

<?php
$customerId = $block->getCustomerId();
echo "Customer ID is ".$customerId;
?>

I Hope This Helps You.

12
  • 1
    this will disable caching for all pages and which i dont want
    – Pramod
    Sep 7, 2020 at 9:48
  • please share your controller block and phtml file i will give you second way to get customer id.
    – Msquare
    Sep 7, 2020 at 9:53
  • block and phtml is already there wait am sharing controller
    – Pramod
    Sep 7, 2020 at 9:54
  • Parse error: syntax error, unexpected 'return' (T_RETURN) in E:\xampp\htdocs\m2\app\code\vedor\module\Controller\Index\Customer.php on line 33
    – Pramod
    Sep 7, 2020 at 10:37
  • 1
    no problem i will find some solution for it thank you for your effort and i dont know who downvoted the ans guyzz do not do that try to understand someones effort between upvoted for the effort thanks
    – Pramod
    Sep 7, 2020 at 11:30

Your Answer

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

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