Pregunta

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!

¿Fue útil?

Solución

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a magento.stackexchange
scroll top