0

I want to set value for an already existing registry variable.

E.g. current_category

I need to set some different value for this registry variable. Could someone kindly elaborate how to do it.

  • 1
    You can try using unregister to unset whats already register and then register your value. If that solves your problem – Gagan May 4 '18 at 5:07
  • Something like this : $category = $this->_objectManager->create('Magento\Catalog\Model\Category')->load($categoryId); if ($category->getId()) { $this->_coreRegistry->register('category', $category); $this->_coreRegistry->register('current_category', $category); } – Nikunj Vadariya May 4 '18 at 5:07
  • @LAW : Many thanks for the suggestion, it worked. Kindly add as an answer so it will benefit many others as well. – Sukeshini May 4 '18 at 5:20
1

You can try using unregister to unset whats already register and then register your value. If that solves your problem

1

Calling Magento\Framework\Registry::register() on an already defined key will throw an exception with the message Registry key "' . $key . '" already exists. You need to unregister the existing key first.

<?php

class MyClass
{
    /**
     * @var \Magento\Framework\Registry
     */
    private $registry;

    /**
     * @param $registry
     */
    public function __construct(\Magento\Framework\Registry $registry)
    {
        $this->registry = $registry;
    }

    /**
     * @param \Magento\Catalog\Api\Data\CategoryInterface $category
     *
     * @return \MyClass
     * @throws \RuntimeException
     */
    public function setCurrentCategory(\Magento\Catalog\Api\Data\CategoryInterface $category): self
    {
        if ($this->registry->registry('current_category')) {
            $this->registry->unregister('current_category');
        }

        $this->registry->register('current_category', $category);

        return $this;
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.