skip to Main Content

can anyone guide me on how I can load or get the product object on the detail tab
https://prnt.sc/t1dpay
I want to display the data on a detail page by loading the product object from
vendor/magento/module-catalog/view/frontend/templates/product/view/details.phtml

Thanks in advance

2

Answers


  1. In Magento there is the MagentoFrameworkRegistry class which contains (among other things) the “current product”, in case of the product detail page that would be the product shown on the page.

    MagentoFrameworkRegistry is deprecated but I’ve not yet found a good alternative. Because it’s deprecated most of the time I create a class which does only one thing, get the desired value from the registry. It’s a middle ground between using the deprecated class itself directly or “rewriting it”, it encapsulates the deprecated class and can be very easily swapped out if necessary in the future (either the whole class or specifically the implementation of get()).

    use MagentoFrameworkRegistry;
    
    class MyCurrentProduct {
        protected $registry;
    
        public function get(): ProductInterface {
            return $registry->get('current_product');
        }
    }
    

    I left some things out of the example because I don’t like posting a copy-pastable answer.

    Login or Signup to reply.
  2. Rather than using the registry, a much better option is to use the product repository.

    Since you wish to grab the current product from the product detail page, that product id is available as a parameter from the URL:

    enter image description here

    You can then use the RequestInterface to grab an instance of the request object, and grab that specific parameter with:

    $productId = $this->request->getParam('id');
    $product = $this->productRepository->getById($productId);
    

    Here’s the full code of doing this with a ViewModel:

    <?php declare(strict_types=1);
    
    namespace MacademyProductInfoViewModel;
    
    use MagentoCatalogModelProductRepository;
    use MagentoFrameworkAppRequestInterface;
    use MagentoFrameworkExceptionNoSuchEntityException;
    use MagentoFrameworkViewElementBlockArgumentInterface;
    
    class MyViewModel implements ArgumentInterface
    {
        public function __construct(
            private RequestInterface $request,
            private ProductRepository $productRepository,
        ) {}
    
        /**
         * @throws NoSuchEntityException
         */
        public function getProduct()
        {
            $productId = $this->request->getParam('id');
            return $this->productRepository->getById($productId);
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search