2

The core uses two deprecated classes to load the current product within the block class on the front end:

  • \Magento\Catalog\Block\Product\AbstractProduct
  • \Magento\Framework\Registry

See: \Magento\Catalog\Block\Product\AbstractProduct::getProduct() and \Magento\Catalog\Block\Product\View\AbstractView::getProduct(). One of many classes that uses these deprecated objects is: Magento\Catalog\Block\Product\View\Type\Simple (declared as product.info.simple in layout XML).

I would like to load a product in a ViewModel without using deprecated tools. How can I do this?

3
  • Don’t load again. You can use their function, in future Magento update that. If you still want to load then try repository
    – Sohel Rana
    Commented May 11, 2019 at 20:06
  • @SohelRana, I should update to say "access". The repository would work but the question is what product to load (currently solved by using the deprecated registry). Commented May 11, 2019 at 23:55
  • 1
    Check github.com/Vinai/module-current-product-example
    – Sohel Rana
    Commented May 12, 2019 at 8:42

1 Answer 1

-1

If you are on product page in Magento 2 then if you want to get current product. So for that you can get current product id like below :

In Controller,Block,Phtml ->

$currentProductId = $this->getRequest()->getParam('id');

In Observer ->

$currentProductId = $observer->getRequest()->getParam('id');

Then load current product by current product id.

If its not correct then please let me know where you want current product.

1
  • $observer->getRequest()->getParam('id') does not work, since getRequest() returns null on observer.
    – Flinth
    Commented Nov 28, 2019 at 17:11

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.