Question

I'm having trouble in getting the customer details using block class. I want to show the customer name after he/she logged in using block class. I can do it via object manager but not through block.

Below are my code:

Block file:

<?php 

namespace vendor\module\Block;

use Magento\Customer\Model\Session;

class Testing extends \Magento\Framework\View\Element\Template {

    public function __construct(
        Session $customerSession,
        \Magento\Framework\View\Element\Template\Context $context
    )
    {
        parent::__construct($context);
        $this->_customerSession = $customerSession;

    }
    public function getCustomerName(){
        $this->_customerSession->getCustomer()->getName();
    }
}

In template file:

<?php echo $block->getCustomerName(); ?>

In XML:

<referenceContainer name="content">
     <block class="vendor\module\Block\Testing" name="customer.session.data" template="Magento_Theme::html/test.phtml" cacheable="false" />
 </referenceContainer>

When I try to load the customer name, its not working.

Any help will be appreciated!

Was it helpful?

Solution

You can use this in your Block file

<?php 

namespace vendor\module\Block;

use Magento\Customer\Model\Session;

class Testing extends \Magento\Framework\View\Element\Template {

    public function __construct(
        Session $customerSession,
        \Magento\Framework\View\Element\Template\Context $context
    )
    {
        parent::__construct($context);
        $this->_customerSession = $customerSession;
    }

    public function getCustomerName(){
        return $this->_customerSession->getCustomer()->getName();
    }


    public function getCustomerId(){
        return $this->_customerSession->getCustomer()->getId();
    }
}

In template file you can direct access your Block file's function like this

<?php echo $block->getCustomerName(); ?>
<?php $customerId =  $block->getCustomerId(); ?>
<img src='<?php echo $this->helper("SK\ProfilePic\Helper\Data")->getProfilePicById($customerId); ?>' alt="Demo">

Because you have used this block class for this template in your XML file here

<block class="vendor\module\Block\Testing" name="customer.session.data" template="Magento_Theme::html/test.phtml" cacheable="false" />

Hope this will help!

OTHER TIPS

You are doing it correctly. You just need to change

this:

public function getCustomerName(){
    $this->_customerSession->getCustomer()->getName();
}

to:

public function getCustomerName(){
    return $this->_customerSession->getCustomer()->getName();
}

You forgot return

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top