Check if customer logged in not working
-
11-10-2020 - |
Frage
I have a block to add link at top based on if customer login like this, when i'm at myaccount page the header link show the right one, but when i go to other page it shows the wrong one, here's my code:
<?php
namespace Namespace\Module\Block;
class Link extends \Magento\Framework\View\Element\Html\Link
{
protected function _toHtml()
{
if (false != $this->getTemplate()) {
return parent::_toHtml();
}
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $objectManager->get('Magento\Customer\Model\Session');
if($customerSession->isLoggedIn()) {
return '<li><a href="/test/loggedin" > Logged In </a></li>' ;
} else {
return '<li><a href="/test/notloggedin" > Not Logged In </a></li>';
}
}
}
Lösung
You have to set cacheable="false"
your module with xml file like this,
<block class="Namespace\Module\Block\Link" name="customname" cacheable="false">
Remove var/generation and clear cache.
Andere Tipps
Simple add this block code in cms or block content
{{block class="Magento\Customer\Block\Account\AuthorizationLink" name="authorization-link" template="account/link/authorization.phtml"/}}
it will show you signin or signout
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit magento.stackexchange