Skip to content

Instantly share code, notes, and snippets.

@DomPixie
Forked from DominicWatts/magento-2-prices.md
Created November 22, 2021 21:04
Show Gist options
  • Save DomPixie/88b3c9032d531f1dbc4993869f2dd7a5 to your computer and use it in GitHub Desktop.
Save DomPixie/88b3c9032d531f1dbc4993869f2dd7a5 to your computer and use it in GitHub Desktop.
Magento 2 Prices
use Magento\Directory\Model\CurrencyFactory $currencyFactory
protected $currencyFactory;
public function __construct(
CurrencyFactory $currencyFactory
) {
$this->currencyFactory = $currencyFactory;
}
/**
* Format price without symbol ['display'=>\Zend_Currency::NO_SYMBOL]
* @param float $price
* @return float
*/
public function formatPrice($price)
{
return $this->currencyFactory
->create()
->format(
$price,
['symbol' => $this->getCurrencySymbol()],
false
);
}
/**
* Get currency from loaded order
* @return void|string
*/
public function getCurrencySymbol()
{
$order = $this->getOrder();
if (!$order || ! $order->getId()) {
return null;
}
$currency = $this->currencyFactory
->create()
->load($order->getOrderCurrency());
if (!$currency) {
return null;
}
return $currency->getCurrencySymbol();
}
use Magento\Framework\Pricing\PriceCurrencyInterface as CurrencyInterface;
protected $currencyInterface;
public function __construct(
CurrencyInterface $currencyInterface
) {
$this->currencyInterface = $currencyInterface;
}
public function formatPrice($price)
{
return $this->currencyInterface->format(
$product->getPrice(),
false,
4
);
}
## Price rendering
<?php
namespace Xigen\Category\Block;
use Magento\Catalog\Pricing\Price\FinalPrice;
use Magento\Framework\Pricing\Render;
use Magento\Catalog\Model\Product;
class Main extends \Magento\Framework\View\Element\Template
{
/**
* Specifies that price rendering should be done for the list of products.
* (rendering happens in the scope of product list, but not single product)
* @return Render
*/
protected function getPriceRender()
{
$layout = $this->getLayout();
$priceRender = $layout->getBlock('product.price.render.default');
if (!$priceRender) {
$priceRender = $layout->createBlock(
Render::class,
'product.price.render.default',
['data' => ['price_render_handle' => 'catalog_product_prices']]
);
}
$priceRender->setData('is_product_list', true);
return $priceRender;
}
/**
* Get product price.
*
* @param Product $product
* @return string
*/
public function getProductPrice(Product $product)
{
$priceRender = $this->getPriceRender();
$price = '';
if ($priceRender) {
$price = $priceRender->render(
FinalPrice::PRICE_CODE,
$product,
[
'include_container' => true,
'display_minimal_price' => true,
'zone' => Render::ZONE_ITEM_LIST,
'list_category_page' => true
]
);
}
return $price;
}
}
[...]
$block->getProductPrice($product);
[...]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment