0

I am getting product using the below code but it is not returning the exact price displayed on product

enter image description here

My code for getting price

$product = $this->productRepository->getById($productId, false, $storeId);
 $productData['price']= $product->getPrice();
3
  • What type of product is it?
    – Nikolas
    Commented Sep 6, 2022 at 7:59
  • It's a simple product Commented Sep 6, 2022 at 8:01
  • I wan't to get the price that is displayed on product , i don't have any custom block I am returung the price using controller Commented Sep 6, 2022 at 8:06

1 Answer 1

0

I created a custom block and call it in my controller

<?php
namespace Vendor\Module\Block\Product;

class Price extends \Magento\Framework\View\Element\Template {
    /** @var  \Magento\Framework\View\Result\Page */
    protected $_product;
    protected $_layout;

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

    public function getPrice(\Magento\Catalog\Model\Product $product)
    {
        $priceRender = $this->getLayout()->getBlock('product.price.render.default');
        if (!$priceRender) {
            $priceRender = $this->getLayout()->createBlock(
                \Magento\Framework\Pricing\Render::class,
                'product.price.render.default',
                ['data' => ['price_render_handle' => 'catalog_product_prices']]
            );
        }
    
        $price = '';
        if ($priceRender) {
            $price = $priceRender->render(
                \Magento\Catalog\Pricing\Price\FinalPrice::PRICE_CODE,
                $product,
                [
                    'display_minimal_price'  => true,
                    'use_link_for_as_low_as' => true,
                    'zone' => \Magento\Framework\Pricing\Render::ZONE_ITEM_LIST
                ]
            );
        }
    
        return $price;
    }
}

Call it in controller

$blockInstance = $this->_objectManager->get('Vendor\Module\Block\Product\Price');
$productData['price']= $blockInstance->getPrice($product);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.