8

This is my code,

   $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
   $customerSession = $objectManager->create('Magento\Customer\Model\Session');

   if ($customerSession->isLoggedIn()) {
        $customerSession->getCustomerId();  // get Customer Id
        $customerSession->getCustomerGroupId();
        $customerSession->getCustomer();
        $customerSession->getCustomerData();
        $myemail=(string)$customerSession->getCustomer()->getEmail();
        echo $myemail;

same code I run Custom module its getting customer email , but, I paste same code other magento core module, Now if condition failed if($customerSession->isLoggedIn()) why? how to solve this problem.

0

6 Answers 6

20

I am facing same problem when Cache enable I am not able to get customer session.But I find below solution

    /**
     * @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());
    }

Use above code in block It is working even cache is enable.

Second Solution:

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>

Add below code in block:

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

    /**
     * Construct
     *
     * @param \Magento\Framework\View\Element\Template\Context $context
     */
    public function __construct(Template\Context $context,
            \Magento\Framework\App\Request\Http $request,
            \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository,
            \Magento\Customer\Model\Session $customerSession
        ) 
    {
        $this->request = $request;
        $this->customerRepository = $customerRepository;
        $this->_customerSession = $customerSession;
        parent::__construct($context);
    }

    public function getOrderData(){
        $customerId = $this->_customerSession->getCustomerId();
        return $customerId;
    }
5
  • It's giving Fatal error Fatal error: Call to undefined method Magento\Customer\Model\SessionFactory::getCustomer() Commented Dec 27, 2016 at 10:12
  • Updated code use it Commented Dec 27, 2016 at 11:46
  • Don't use cacheable="false" in your XML as it will make the entire page not cacheable. (unless this is what you want)
    – jsims281
    Commented Apr 8, 2019 at 6:47
  • Never use cachable='false' in header files. It will forbid caching for all the pages because header is included on all pages. Wrong approach Commented Jul 17, 2019 at 7:33
  • @AhsanHorani Already I have given two solution, second solution only for knowledge Commented Jul 18, 2019 at 18:26
3

That is not the correct way to do it. Using create you are going to instantiate a new object instead of getting the actual session.

It is the same difference as using getModel instead of getSingleton in Magento 1.

Option 1 (the correct option in Magento2):

Use __construct injection to get Magento\Customer\Model\Session:

protected $customerSession;
...
public function __construct(
  \Magento\Customer\Model\Session $customerSession
) {
   $this->customerSession = $customerSession;
}
...
public function yourMethod()
{
  if ($this->customerSession->isLoggedIn()) {
  ...
  }
}
...

Option 2 (working, but not suggested):

Use get instead of create:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $objectManager->get('Magento\Customer\Model\Session');
3
1

use customer helper instead

Magento\Customer\Helper\Session\CurrentCustomer

to get logged in flag, you can approach with getCustomerId

0

You can try by creating an object of objectManager and should not use objectManager directly.

Use something like,

class Example extends \Magento\Framework\View\Element\Template
{
    private $_objectManager;
    public function __construct(
        \Magento\Framework\ObjectManagerInterface $objectmanager
    ){
        $this->_objectManager = $objectmanager;
    }

    public function getExample()
    {
        $customerSession = $this->_objectManager->create("Magento\Customer\Model\Session");
        if ($customerSession->isLoggedIn()) {
            $customerData = $customerSession->getCustomer()->getData();
            /*Your logic*/
        }
    }
}
0

This is a solution.

<?php
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $customerSession = $objectManager->get('Magento\Customer\Block\Account\Customer');
?>
<?php if($customerSession->customerLoggedIn()): ?>
    <span data-bind="scope: 'customer'"><span data-bind="text: customer().firstname"></span></span>
    <script type="text/x-magento-init">
      {
        "*": {
            "Magento_Ui/js/core/app": {
                "components": {
                    "customer": {
                        "component": "Magento_Customer/js/view/customer"
                    }
                }
            }
        }
      }
    </script>
<?php endif; ?>
0

Thanks very much!This can solve my question!

get('Magento\Customer\Block\Account\Customer'); ?> customerLoggedIn()): ?>
<span data-bind="scope: 'customer'"><span data-bind="text: customer().firstname"></span></span>
<script type="text/x-magento-init">
  {
    "*": {
        "Magento_Ui/js/core/app": {
            "components": {
                "customer": {
                    "component": "Magento_Customer/js/view/customer"
                }
            }
        }
    }
  }
</script>

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.