0

I need to show a Block on my product detail page when the customer is not logged in only.
What is the best way to achieve that in Magento 2.3?
Thanks in advance!

1
  • have you use custom Module file ? share your block and phtml file
    – Msquare
    Mar 30, 2020 at 9:32

2 Answers 2

1

Please add the following code in your block file Eg:CustomBlock.php

<?php
namespace [vendor_name]\[module_name]\Block;
class CustomBlock extends \Magento\Framework\View\Element\Template
{
    protected $_customerSession;

    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Customer\Model\SessionFactory $customerSession,
        array $data = []
    ) {
        $this->customerSession = $customerSession;
        parent::__construct($context, $data);
    }
  public function isCustomerLoggedIn()
  {
    $customer = $this->customerSession->create();
        if(!($customer->isLoggedIn()))
             return true;
        return false;
  }    
}

?>

and kindly add the following code in your template file

<?php
$checkCustomer = $block->isCustomerLoggedIn();
if($checkCustomer):
   echo "<b>Please Login!! </b>";
endif;
?>

Hope this helps you.

2
  • Thanks that is working :-)!
    – Th. Schott
    Mar 30, 2020 at 13:38
  • Welcome!! :) @schotti
    – Moni Raj
    Mar 31, 2020 at 4:03
0

There is a quick and dirty way that works (tested in 2.4.3-pl), but it uses ObjectManager which is not recommended as best practice. Just stick this in the .phtml file you want it to work in.

<?php
$checkCustomer = \Magento\Framework\App\ObjectManager::getInstance()->get(\Magento\Customer\Model\Session::class);

if($checkCustomer->isLoggedIn()) {
    //DO YOUR THANG HERE
}
?>

Personally, I don't fully understand why doing it like this is "bad" (perhaps someone could enlighten me below), but obviously it's up to the developer how they achieve what they're on a deadline to achieve.

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.