0

I want to have a block in home page that show text and button if customer is not logged in and if he is logged in this block have to disapear so how to proceed any help please here is my code in .phtml

<?php $objectManagerlogin = \Magento\Framework\App\ObjectManager::getInstance(); $customerSession = $objectManagerlogin->get('Magento\Customer\Model\Session'); $baseurl = $objectManagerlogin->get('Magento\Store\Model\StoreManagerInterface')->getStore(0)->getBaseUrl(); ?> <?php if(!$customerSession->isLoggedIn()) :?> <div class="title-home-page"> <?= /* @escapeNotVerified */ __('You have to be a member to see the content of this Page!!! To be one of our members click <a href="%1" class="action submit primary">here</a>', $baseurl .'customer/account/create') ?> </div>

Developper Magento
  • 1,603
  • 2
  • 14
  • 47

3 Answers3

1

Using the object manager directly seems easier but it's not the right way, you can see this

The right way is to inject for exemple \Magento\Customer\Model\Session in your block.

app/code/Vendor/Name/Block/Blockname.php

protected $_session;

public function __construct(
    ...
    \Magento\Customer\Model\Session $session,
    ...
) {
    ...
    $this->_session = $session;
    ...
}

public function isCustomerLoggedIn()
{
    return $this->_session->isLoggedIn();
}

Then in your phtml : (the file should be in the module)

<?php if (!$block->isCustomerLoggedIn()) : ?>
    <div>Your div content here</div>
<?php endif; ?>

In the case that your file is not in the module but in template, you can get it like this:

<?php $moduleBlock= $block->getLayout()->createBlock('Vendor\Name\Block\Blockname'); ?>

<?php if (!$moduleBlock->isCustomerLoggedIn()) : ?>
    <div>Your div content here</div>
<?php endif; ?>
PЯINCƎ
  • 11,669
  • 3
  • 25
  • 80
1

If using Varnish cache or full page cache, building the logic inside the block will not work properly.

Take a look at the header, you will see Magento is using JS logic.

So, my suggestion is to use Ajax or based on local storage data.

In your case, I think you should use Ajax.

Khoa TruongDinh
  • 32,054
  • 11
  • 88
  • 155
0

In home page template file, please check whether the customer logged in or not.

Following code you can check customer login or not anywhere

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $objectManager->get('Magento\Customer\Model\Session');
if($customerSession->isLoggedIn()) {
   // customer login action
}

From controller

$this->_objectManager->get('Magento\Customer\Model\Session');
if($customerSession->isLoggedIn()) {
   // customer login action
}
Kavitha mano
  • 351
  • 3
  • 11