skip to Main Content

I want to get the current product information in a controller.

I created a function in block, and called that function in my phtml file.

How can I accomplish this task?

2

Answers


  1. With reference from this article – https://www.atwix.com/magento-2/alternatives-for-deprecated-registry-class-magento-2-3/

    You can:

    1. Add MagentoCatalogModelSession into the contructor of your controller so that it can instantiate the catalog session object:
        public function __construct(
                Context $context,
                MagentoCatalogModelSession $catalogSession
               ) {
                $this->catalogSession = $catalogSession;
                parent::__construct($context);
               }
    
    1. In the execute method of the controller to get the ProductId use:
        $productId = $this->catalogSession->getData('last_viewed_product_id');
    
    1. With Product Id, you can load the product data:
        $product = $this->productFactory->create()->load($productId);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search