Question

I'm trying to retrieve the current product's attributes in a block in Magento 2.

I can get a product, like ID 1:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager
               ->create('\Magento\Catalog\Model\ProductRepository')
               ->getById(1);

I don't know how to get the ID of the current product though.

How could I do that?

Was it helpful?

Solution

In order to get the current product, one of the recommended ways is:

  1. Extend or use block class: Magento\Catalog\Block\Product\View\AbstractView.
  2. Get product using: $block->getProduct() in your phtml file.

OTHER TIPS

Although other answers are correct, they're not the recommended/proper solution either.

Using the ObjectManager is absolutely prohibited in Magento 2. So please don't rely on this solution, but use proper DI to achieve this instead. To learn how to use DI in Magento 2, see this resource: http://devdocs.magento.com/guides/v2.0/extension-dev-guide/depend-inj.html

Extending AbstractView is not necessary. If you look at the original function in the AbstractView, you can see Magento used the registry to fetch the product. You don't need to extend a specific class to do this, simply inject Magento\Framework\Registry into your constructor and request the "product" registry item.

Full code example:

<?php

// Example = Module namespace, Module = module name, rest of the namespace is just for example only, change this to whatever it is in your case.
namespace Example\Module\Block\Frontend\Catalog\Product\General;

use Magento\Catalog\Model\Product;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Registry;
use Magento\Framework\View\Element\Template;

class Information extends Template
{

    /**
     * @var Registry
     */
    protected $registry;

    /**
     * @var Product
     */
    private $product;

    public function __construct(Template\Context $context,
                                Registry $registry,
                                array $data)
    {
        $this->registry = $registry;

        parent::__construct($context, $data);
    }


    /**
     * @return Product
     */
    private function getProduct()
    {
        if (is_null($this->product)) {
            $this->product = $this->registry->registry('product');

            if (!$this->product->getId()) {
                throw new LocalizedException(__('Failed to initialize product'));
            }
        }

        return $this->product;
    }

    public function getProductName()
    {
        return $this->getProduct()->getName();
    }

}

If you are using Magento 2.1 or major, you can use this helper because the old method was deprecated.

...
use Magento\Catalog\Helper\Data;
...

public function __construct(
        Context $context,
        Data $helper,
        array $data = []
    ){
        $this->context = $context;
        $this->helper = $helper;
        $this->data = $data;
        parent::__construct($context, $data);
    }

...

public function getProduct(){
    if(is_null($this->_product)){
        $this->_product = $this->helper->getProduct();
    }
    return $this->_product;
}

@Wesley Vestjens solution worked for me as well. Just make sure to pay attention to the access modifier, as private might not be what you want if you are using getProduct() in your template. In the above example it works as getProductName() is the public method to use.

As mentioned "ObjectManager is absolutely prohibited" and "Registry is deprecated", the following atwix registry alternative appears to represent the current correct approach to the original question by using Service and ViewModel.

https://www.atwix.com/magento-2/alternatives-for-deprecated-registry-class-magento-2-3/

https://github.com/Atwix/atwix-blog-magento2-registry-deprecated-solutions

Get Product Service: https://github.com/Atwix/atwix-blog-magento2-registry-deprecated-solutions/blob/master/app/code/Atwix/RegistryAlternative/Service/GetCurrentProductService.php

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top