5

User logged in or not checking not works in other pages such as Product, Category and other static pages but its works well on customer pages like Dashboard, Address book, Orders etc...

Here is my helper: app/code/MyVendor/MyUserModule/Helper/Data.php

<?php 
        namespace MyVendor\MyUserModule\Helper;
        class Data extends \Magento\Framework\App\Helper\AbstractHelper
        {

            public function __construct(
                \Magento\Framework\App\Helper\Context $context,
                \Magento\Customer\Model\Session $customerSession
            ) {
                $this->customerSession = $customerSession;
                parent::__construct($context);
            }

            public function isLoggedIn()
            {
                return $this->customerSession->isLoggedIn();
            }
            public function userLoggedDetails()
            {
                return $this->customerSession->getCustomer();
            }
        }
?>

And phtml like this

<?php 
    $customerSession = $this->helper('MyVendor\MyUserModule\Helper\Data');
    if($customerSession->isLoggedIn()) {
        echo "Welcome ".$customerSession->userLoggedDetails()->getName();
    }else{
        echo "Login";
    }
?>

Also I noticed logged in or not checking works well on all pages while call ObjectManager directly, like this way

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

but this method not recommended by experts, so should follow Constructor injecting proper method, Anyone know what I missed, please.

2
  • If you enable full page cache, it stills working well? Commented Sep 22, 2016 at 12:31
  • @KhoaTruongDinh I already enabled all caches from admin, is any other cache place have to enable? Commented Sep 22, 2016 at 15:34

1 Answer 1

2

Finally I got the answer, the problem with block cache, to get real Magento session, specific block cache must be false!

I did following changes and worked well:

  1. Added $this->_isScopePrivate = true; in my __construct
  2. Added attribute cacheable="false" to my block which belongs-to my template .phtml
2
  • Where you add the cacheable="false" ? I have same issue with Magento 2.1 but I do not know where to add attribute and how should look complete file. Commented Apr 4, 2017 at 18:44
  • 1
    @GeorgeGeorge add cacheable="false" in your layout xml for the curresponding block. In my case on this file, /app/design/frontend/My_vendor/my_theme/Magento_Theme/layout/default.xml I have to add this block <block class="Magento\Framework\View\Element\Template" name="usermenu.us.li" template="Magento_Theme::html/user_nav_us_li.phtml" before="-" cacheable="false"/> Commented Apr 6, 2017 at 7:00

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.