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 ?
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 ?
In Magento 2 proposed to use service layer for this.
Try use \Magento\Catalog\Model\ProductRepository::getById
method to get product by 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 skuMagento 2 recommends to use Factories
for loading all Models. Here is how you should do it:
Above your class add this line:
use Magento\Catalog\Model\ProductFactory;
Now create class property:
protected $productFactory;
In your constructor, add dependency:
public function __construct(
ProductFactory $productFactory
) {
$this->productFactory = $productFactory;
}
Now load product as below:
$_product = $this->productFactory->create()->load(<product_id>);
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();
$this->getProduct()
as this is responsible to bring the product object.