1

I'm trying to inject customer session in my block:

use Magento\Framework\View\Element\Template;
use Magento\Customer\Model\Session;

class Header
extends Template
{
protected $session;

public function __construct(
    Template\Context $context,
    Session $customerSession
)
{
    $this->session = $customerSession;
    parent::__construct($context);
}

public function getBaseUrl(){
    return $this->_storeManager->getStore()->getBaseUrl();
}

public function isCustomerLogged()
{
    if($this->session->isLoggedIn())
        return "yes";
    else
        return "no";
}

public function getLoggedCustomerName(){
    return $this->session->getCustomer()->getFirstName();
}
}

Updated question

$this->session->isLoggedIn() always returns false whereas in controller, it returns true. The Context namespaces are different for both:

use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Element\Template\Context;

Please help

1 Answer 1

1

Your constructor is missing the parent call that does a lot more initialisation work. It needs to look like the following;

public function __construct(
    Template\Context $context,
    \Magento\Customer\Model\Session $customerSession,
    array $data = []
) {
    $this->customerSession = $customerSession;
    parent::__construct($context, $data);
}
1
  • Oops, silly mistake, thanks a lot Smartie :) Commented Jan 5, 2016 at 14:55

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.