4

I want to get Product name in Phtml file and i checked this three collection but in that there are no product name available.

$productCollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\Collection');
$productPrice = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$productimageCollection = $objectManager->create('Magento\Catalog\Api\ProductRepositoryInterfaceFactory');
9

You need to load product to get product name

With Object Manager

$productId = "10"; //Product Id

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

echo $product->getName(); //Get Product Name

Note: Don't use objectManager directly

With Factory Method

<?php

  protected $product;  

  public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Catalog\Model\ProductFactory $product
    ) {
        $this->product = $product;
        parent::__construct($context);
    }

    public function getProduct($id)
    {
        return $this->product->create()->load($id);
    }

}

Then call getProduct function in your phtml file

$productId = "10"; //Product Id
$product=$this->getProduct($productId);

echo $product->getName(); //Get Product Name
1

try this

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

You can use following code in phtml.

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

$productCollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');

$collection = $productCollection->create()
            ->addAttributeToSelect('*')
            ->setPageSize(3) //Selecting 3 products
            ->load();

foreach ($collection as $product){
     echo 'Name  =  '.$product->getName().'<br>';
}  
  • this method not working for product collection.. – aravind Nov 27 '17 at 6:14
0

Use Factory and inject Magento\Catalog\Model\ProductFactory product factory in your file.That is best coding standard.

protected $product;  

  public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Catalog\Model\ProductFactory $product
    ) {
        $this->product = $product;
        parent::__construct($context);
    }

    public function getProduct($id)
    {
        return $this->product->create()->load($id);
    }

}

$productId = "1256"; //Your Product Id
$product=$this->getProduct($productId);

echo $product->getName();

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.