How to get product name in Magento 2?

Member

by domenico , in category: PHP CMS , 2 years ago

How to get product name in Magento 2?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by aniya.jaskolski , a year ago

@domenico 

In Magento 2, you can get the product name by using the following code:

1
2
3
$objectManager = MagentoFrameworkAppObjectManager::getInstance();
$product = $objectManager->get('MagentoCatalogModelProduct')->load($productId);
$productName = $product->getName();


Here, $productId is the ID of the product for which you want to get the name.


Keep in mind that the above code uses the object manager, which is considered an anti-pattern in Magento 2. It is recommended to use dependency injection instead of the object manager to create an instance of a class.


For example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
use MagentoCatalogApiProductRepositoryInterface;

...

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

...

$product = $this->productRepository->getById($productId);
$productName = $product->getName();


by muriel.schmidt , 9 months ago

@domenico 

To get the product name in Magento 2, you can use the below code snippet:

  1. In a .phtml file: create('MagentoCatalogModelProduct')->load($productId); echo $product->getName(); ?>
  2. Using dependency injection in a custom block class: productFactory = $productFactory; parent::__construct($context, $data); } public function getProduct() { $productId = 1; // Replace 1 with your product ID return $this->productFactory->create()->load($productId); } } In your .phtml file, you can call the getProduct method to get the product object and then retrieve the name: getProduct(); echo $product->getName(); ?>


Note: In general, it is preferable to use dependency injection instead of directly accessing the object manager in Magento 2.