3

below is my block file code

class View extends \Magento\Framework\View\Element\Template 
{ 
protected $_registry;
protected $_customerSession; 
protected $_customer; 
public function __construct(
    \Magento\Framework\App\Action\Context $context,
    \Magento\Framework\Registry $registry,
    \Magento\Customer\Model\Session $customerSession, 
    \Magento\Customer\Model\Customer $customer      
) {
    $this->_registry = $registry;
    $this->_customerSession = $customerSession; 
    $this->_customer = $customer; 
    parent::__construct($context);
}

public function getUser()
{
    if (!$this->_loadValidUser()) {
        return;
    }
    return $this->registry->registry('current_user');
}   

protected function _loadValidUser($userId = null)
{
     $userId = (int) $this->getRequest()->getParam('user_id');
    try {
        $user = $this->_customer->load($userId);
        $this->registry->register('current_user', $user);            
        return $user;
    }catch (Exception $e) {
       print_r($e->getMessage());
         return false;
    }

}

}

What is the mistake in above construction? I am getting the error like

PHP Fatal error: Uncaught TypeError: Argument 1 passed to Magento\Framework\View\Element\Template

kunj
  • 3,699
  • 2
  • 10
  • 25
Jafar Pinjar
  • 1,929
  • 7
  • 64
  • 139

2 Answers2

2

Try this:

public function __construct(
    \Magento\Framework\View\Element\Template\Context $context,
    \Magento\Framework\Registry $registry,
    \Magento\Customer\Model\Session $customerSession,
    \Magento\Customer\Model\Customer $customer       
){
    $this->_registry = $registry;
    $this->_customerSession = $customerSession;
    $this->_customer = $customer;
    parent::__construct($context);
}

after that changes please run below commands

php bin/magento cache:flush and php bin/magento setup:di:compile

kunj
  • 3,699
  • 2
  • 10
  • 25
1

Use this code in your block file :

protected $_customerSession;

public function __construct(
    ......
    \Magento\Framework\View\Element\Template\Context $context,
    \Magento\Customer\Model\SessionFactory $customerSession,
    array $data = []
    ......
)
{
    ......
    $this->_customerSession = $customerSession->create();
    parent::__construct($context, $data);
    ......
}

public function getCustomerData() {
    if ($this->_customerSession->isLoggedIn()) {
        return $this->_customerSession->getCustomerData();
    }
    return false;
}

and display in your phtml file :

$customerData = $block->getCustomerData();
echo "<pre/>";
print_r($customerData);
Rohan Hapani
  • 17,388
  • 9
  • 54
  • 96