Magento 2 – Set and Get Registry Values

event-observermagento-2.1.8magento2registerregistry

I want to set an array in registry in controller_action_predispatch_checkout_cart_add event observer and read this in a phtml page.

The following code will give blank result
.

=> Code :

namespace NameSpace\Module\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\RequestInterface;

class RestrictAddToCart implements ObserverInterface
{
    protected $_request;  

    protected $_product;  

    protected $_responseFactory;

    protected $_url;
    protected $_registry;

    public function __construct(
        RequestInterface $request,
        \Magento\Catalog\Model\Product $product,
        \Magento\Framework\App\ResponseFactory $responseFactory,
        \Magento\Framework\Registry $registry,
        \Magento\Framework\UrlInterface $url
    )
    {
        $this->_request = $request;
        $this->_product = $product;
        $this->_registry = $registry;
        $this->_responseFactory = $responseFactory;
        $this->_url = $url;
    }

    public function execute(\Magento\Framework\Event\Observer $observer)
    {          
        $this->_registry->register('slct_options', $observer->getRequest()->getParams());
        $customRedirectionUrl = $this->_url->getUrl('my-page');            
        $this->_responseFactory->create()->setRedirect($customRedirectionUrl)->sendResponse();     
        die(); 
        return $this;
    }
}

=> phtml :

<?php 
print_r( $block->getRegisterData());     
 ?>

=> Block :

namespace Namespace\Module\Block;

use \Magento\Framework\View\Element\Template;

class Customblock extends Template
{    
    protected $_registry;

    public function __construct(
        Template\Context $context,
        \Magento\Framework\Registry $registry,
        array $data = [])
    {
        $this->_registry = $registry;
        parent::__construct($context, $data);
    }           
     public function getRegisterData()
    {         
        return $this->_registry->registry('slct_options');    
    }
}

Best Answer

The registry is getting 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 instead.

Related Topic