Could someone advise what's the best way to get the current product in a custom helper? Basically if I am a product page I need to get it's sku
-
Helpers are usually used as elements/methods that are global and always available. Helpers can be called anywhere and you only need to inject them in the class. I think you should create a block class which should have the code as per shared in answer below. That shall solve the problem for you.– GaganCommented Sep 13, 2018 at 13:28
Add a comment
|
2 Answers
protected $_registry;
public function __construct(
\Magento\Framework\App\Helper\Context $context
\Magento\Framework\Registry $registry
)
{
$this->_registry = $registry;
parent::__construct($context);
}
public function getCurrentProduct()
{
return $this->_registry->registry('current_product');
}
-
I always get the response of null when I call this. Could you advise anymore?– Goose84Commented Sep 13, 2018 at 8:02
-
@Goose84 i am not sure about it but please refer magento.stackexchange.com/questions/44299/… it may help you thanks Commented Sep 13, 2018 at 8:07
To get the current product:
use block class: Magento\Catalog\Block\Product\View
Get product using: $block->getProduct() in your phtml or use the class and get in the block file.
Hope it Helps.Happy coding!!