3

I have registered a variable in customer checkout view template link.phtml with code:

<?php 
$_objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$registry = $_objectManager->get('Magento\Framework\Registry');
$reg_val = $registry->register('user_not_logged', '1');
?>

Again I wanted to access that registry through customer overridden controller createPost.php

 1. Defined protected variable :
   protected $_coreRegistry;
 2. passed in constructor 
  \Magento\Framework\Registry $coreRegistry; 
 3. Accessed coreRegistry object using :
   $this->_coreRegistry = $coreRegistry;
 4. Inside execute() function
   $user_logged_registry = $this->_coreRegistry->registry('user_not_logged');
   var_dump($user_logged_registry);

This returns me NULL.

Can anybody explain me why I couldn't access the value of registered variable in controller.

1 Answer 1

0

The registry is cleared after the server sends a response. Each new request starts with an empty registry. If you want to transfer data from one request to another you should use the session (\Magento\Customer\Model\Session) instead:

In block:

protected $session;

public function __construct(
    ...
    \Magento\Customer\Model\Session $session, 
    ...
){
    ...
    $this->session = $session;
    ...
}

public function getCustomersSession()
{
    return $this->session;
}

In template:

$block->getCustomersSession()->setData('user_not_logged', '1');

In controller:

protected $session;

public function __construct(
    ...
    \Magento\Customer\Model\Session $session, 
    ...
){
    ...
    $this->session = $session;
    ...
}

public function execute()
{
    ...
    $isUserLoggedIn = $this->session->getData('user_not_logged');
    ...
}

Or using objectManager if you can not modify the __construct method:

$_objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$session = $_objectManager->get('Magento\Customer\Model\Session');
4
  • Thanks. @Siarhey Uchukhlebau, I was unknown that registry is cleared after the server sends a response. I kept on looking the result with such circumstances. Your code and concept really worked for my work. You saved by time. May 15, 2017 at 14:17
  • @sagarsapkota I'm glad to help you :) May 15, 2017 at 14:47
  • How to access current user? like we use in m1 Mage::registry('current_user'); same how can we use in m2? Aug 6, 2018 at 8:53
  • @jafar You can use the getCustomer() method of the \Magento\Customer\Model\Session class, like this: $this->session->getCustomer();. This customer-instance will be obtained using a singleton, as like with a registry. Aug 7, 2018 at 6:33

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.