I am new to magento2 and currently I'm building a custom module and i want to get the product ID/SKU from the catalog. I'm trying to call using a function located in the Block folder. please advise!

有帮助吗?

解决方案

Try this:

<?php 
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $product = $objectManager->get('Magento\Framework\Registry')->registry('current_product');//get current product
    echo $product->getId();
    echo $product->getName();
?>

OR

Add bellow code in your block file.

for example app/code/AR/CustomModule/Block/CustomBlock.php

<?php
namespace AR\CustomModule\Block;
class CustomBlock extends \Magento\Framework\View\Element\Template
{
    protected $_registry;

    public function __construct(
        \Magento\Backend\Block\Template\Context $context,       
        \Magento\Framework\Registry $registry,
        array $data = []
    )
    {       
        $this->_registry = $registry;
        parent::__construct($context, $data);
    }

    public function _prepareLayout()
    {
        return parent::_prepareLayout();
    }

    public function getCurrentCategory()
    {       
        return $this->_registry->registry('current_category');
    }

    public function getCurrentProduct()
    {       
        return $this->_registry->registry('current_product');
    }   

}
?>

Printing current product data in your template (custom.phtml) file

if ($currentProduct = $block->getCurrentProduct()) {
    echo $currentProduct->getName() . '<br />';
    echo $currentProduct->getSku() . '<br />';
    echo $currentProduct->getId() . '<br />';       
}

其他提示

<?php 
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->get('Magento\Framework\Registry')->registry('current_product');//get current product
echo $product->getId();
echo $product->getName();
?>

This works for me.

.

<?php
     $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
     $productid = $this->getRequest()->getParam('id');                                       
     $product = $objectManager->create('Magento\Catalog\Model\Product')->load($productid);
     echo $product;
?>                                                                          

use this code for to get current product id

You could try $product = $this->abstractProduct->getProduct();

with \Magento\Catalog\Block\Product\AbstractProduct $abstractProduct

worked for me :)

<?php 
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $product = $objectManager->get('Magento\Framework\Registry')->registry('current_product');
    echo $product->getId();
    echo $product->getName();
    echo $product->getSku();

?>

Try this:

<?php  
   $productId = 8;
   $objectManager =  \Magento\Framework\App\ObjectManager::getInstance();
   $currentproduct = $objectManager->create('Magento\Catalog\Model\Product')->load($productId);
   echo $currentproduct->getName(); 
?>
许可以下: CC-BY-SA归因
scroll top