2

Hi i have a product id 22 . I want to get the product details by this id . in this page

default/Magento_Catalog/templates/category/Products.phtml

Example :

$product=get_product_details(22);

I want to create an object `$products using this id so i can call the built in functions like

$product->getProductUrl()
$product->getName()

Is there any built in function available ?

  • You are using custom file Products.phtml to display products? – Sumit Aug 27 at 11:57
  • I will suggest you to use view model for this functionality – Ansar Husain Aug 27 at 12:00
1

Object manager method:

$product_id = "Your Product Id";
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->create('Magento\Catalog\Model\Product')->load($product_id);

Factory Method

<?php
namespace Test\Module\Block;

class Product extends \Magento\Framework\View\Element\Template
{

  protected $_productloader;  


  public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Catalog\Model\ProductFactory $_productloader

    ) {
        $this->_productloader = $_productloader;
        parent::__construct($context);
    }
    public function getLoadProduct($id)
    {
        return $this->_productloader->create()->load($id);
    }

}

You can load product data by adding below content to your phtml file.

$product = $block->getLoadProduct(22);
echo $product->getName();
echo $product->getProductUrl();
  • thank you very much – John Aug 27 at 12:08
  • You're welcome. Happy coding!!! – Sumit Aug 27 at 12:09
0

you can use the below code to get the product using product id

$product_id=22;
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->create('Magento\Catalog\Model\Product')->load($product_id);
  • thank you very much – John Aug 27 at 12:08
0

Try with below id get product details using below code :

$product_id=22;
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->create('Magento\Catalog\Model\Product')->load($product_id);

than try with below code

$product->getData();

than getting response

if you want short_description than use $product->getShortDescription() for all you can use which are listed in getData()

  • thank you very much – John Aug 27 at 12:08
0

Using ObjectManager is not recommended. I would suggest you to use block class or create a view Model and define your methods there. That way your code will follow the best practices

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.