Hello Everyone,
In this blog, we will learn about how to get Currency Data like Code, Rate, Symbol in Magento 2.
We fetch current currency, base currency, default currency and allowed currency.
Without wasting your time, let us guide you straight away. Follow the easy step given below to get Currency Data in Magento 2.
STEPS FOR GET CURRENCY DATA: CODE, RATE, SYMBOL IN MAGENTO 2
Step 1: Create Get Currency Data.php file
app/code/Vendor/Extension/Block/GetCurrencyData.php
<?php
namespace Vendor\Extension\Block;
use Magento\Backend\Block\Template\Context;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Directory\Model\Currency;
class GetCurrencyData extends \Magento\Framework\View\Element\Template
{
protected $storeManager;
protected $currency;
public function __construct(
Context $context,
StoreManagerInterface $storeManager,
Currency $currency,
array $data = [])
{
$this->storeManager = $storeManager;
$this->currency = $currency;
parent::__construct($context, $data);
}
public function getCurrentStore()
{
return $this->storeManager->getStore();
}
public function getBaseCurrencyCode()
{
return $this->getCurrentStore()->getBaseCurrencyCode();
}
public function getCurrentCurrencyCode()
{
return$this->getCurrentStore()->getCurrentCurrencyCode();
}
public function getDefaultCurrencyCode()
{
return $this->getCurrentStore()->getDefaultCurrencyCode();
}
public function getAvailableCurrencyCodes($BaseNotAllowed = false)
{
return $this->getCurrentStore()->getAvailableCurrencyCodes($BaseNotAllowed);
}
public function getAllowedCurrencies()
{
return $this->getCurrentStore()->getAllowedCurrencies();
}
public function getCurrentCurrencyRate()
{
return $this->getCurrentStore()->getCurrentCurrencyRate();
}
public function getCurrentCurrencySymbol()
{
return $this->currency->getCurrencySymbol();
}
}
Step 2: Create currencyData.phtml file
app/code/Vendor/Extension/view/frontend/templates/currencyData.phtml
<?php
echo $block->getCurrentCurrencySymbol() . '<br />';
echo $block->getCurrentCurrencyCode() . '<br />';
echo $block->getBaseCurrencyCode() . '<br />';
echo $block->getDefaultCurrencyCode() . '<br />';
echo $block->getCurrentCurrencyRate() . '<br />';
print_r($block->getAvailableCurrencyCodes()) . '<br />';
print_r($block->getAllowedCurrencies()) . '<br />';
Step 3: Finally run the below commands
$ php bin/magento cache:clean
$ php bin/magento cache:flush
Final Thoughts:
So this was the easiest way which we have told you in this blog. This is how you can get Currency Data in Magento 2. Hope you liked the blog.
So quickly go to the comment box and tell me how you like this blog?
Stay tuned with us on our site to get new updates of Magento.
Thanks for reading and visiting our site.
