1

There are a quite a lot of classes responsible for displaying prices, as well as tutorials about it.

How to display just simple price for downloadable product in custom block/template? Is there any preferable way? I think it would be nice to include some models if needed for DI of my block.

0

The best way to get the price from a product is through the Magento\Catalog\Model\Product::getFinalPrice() method. This method caches the price in the model once it has been calculated, and queries the price model if it has not been calculated yet.

If you already have a product model instance, you can just use that. If not, the current product can be accessed through the registry, or loaded through an instance of the Magento\Catalog\Api\ProductRepositoryInterface, so long as you have the ID for it.

Please let me know if anything doesn't make sense!

| improve this answer | |
  • the problem is not to obtain value of price - I know these methods - question is about displaying it. Final price displays a lot of zeros and I don't feel the treating it as normal integer and just trim zero and add sign of $ is proper way to display price. – Bartosz Kubicki Jan 12 '17 at 14:56
0

Actually I have found nice way (not sure if best one) in vendor/magento/module-catalog/Block/Product/ListProduct.php:350:

/**
 * @param \Magento\Catalog\Model\Product $product
 * @return string
 */
public function getProductPrice(\Magento\Catalog\Model\Product $product)
{
    $priceRender = $this->getPriceRender();

    $price = '';
    if ($priceRender) {
        $price = $priceRender->render(
            \Magento\Catalog\Pricing\Price\FinalPrice::PRICE_CODE,
            $product,
            [
                'include_container' => true,
                'display_minimal_price' => true,
                'zone' => \Magento\Framework\Pricing\Render::ZONE_ITEM_LIST,
                'list_category_page' => true
            ]
        );
    }

    return $price;
}

/**
 * @return \Magento\Framework\Pricing\Render
 */
protected function getPriceRender()
{
    return $this->getLayout()->getBlock('product.price.render.default');
}

Using first method in template we can get nice price string. What is more this one can be placed in any blocks as it only dependence is from AbstractBlock ($this->getLayout()).

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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