Question

I want to use functions like getName(), getPrice(), etc. of product to retrieve product information in Magento 2.

Can anyone show me how can I achieve that ?

Was it helpful?

Solution

In Magento 2 proposed to use service layer for this. Try use \Magento\Catalog\Model\ProductRepository::getById method to get product by id

OTHER TIPS

Magento 2 recommends to use Factories for loading all Models. Here is how you should do it:

  1. Above your class add this line:

    use Magento\Catalog\Model\ProductFactory;
    
  2. Now create class property:

    protected $productFactory;
    
  3. In your constructor, add dependency:

    public function __construct(
       ProductFactory $productFactory
    ) {
       $this->productFactory = $productFactory;
    }
    
  4. Now load product as below:

    $_product = $this->productFactory->create()->load(<product_id>);
    

On top of others answers, I highly suggest using the following service contracts methods:

  • \Magento\Catalog\Api\ProductRepositoryInterface::getById : to load a product by id
  • \Magento\Catalog\Api\ProductRepositoryInterface::get : to load a product by sku

The more Magento way of achieving this, although it's hard to tell since they most places throughout the core code do it differently is to use the product repository.

use Magento\Catalog\Model\ProductRepository;

protected $productRepository;

public function __construct(
   ProductRepository $productRepository
) {
   $this->productRepository = $productRepository;
}

public function getMyProduct($productId)
{
    return $this->productRepository->getById($productId);
}

for this you must use below

use \Magento\Catalog\Model\Resource\Product\CollectionFactory

$prod_id = "Your product id goes here";
$om         =   \Magento\Framework\App\ObjectManager::getInstance();
$pdata =   $om->create('Magento\Catalog\Model\Product')->load($prod_id);

I have fetch product details using function in product view page like below.

Here Sm/Sawyer is my theme.

$_config = $this->helper('Sm\Sawyer\Helper\Data');
$productId = $this->getProduct()->getId();
$name = $this->getProduct()->getName();
$stock1 = $this->getProduct()->getQty();
$price = $this->getProduct()->getPrice();
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top