0
votes

I have 2 currencies in my Magento 2 website. USD is the base currency and SAR (SAR) is the second currency. In my website header there is a drop down where the user can select the currency of the store. When the user visits the website he can see every product value in USD, and if the user changes the currency in the drop down to riyal, then he can see every product value in SAR.

Now I have a requirement for a user who is visiting the website from Saudi. He needs to see the store in SAR currency. For that I have written a module and it is working fine.

My problem is that if a user visits and tries to change the store currency in the dropdown, the page reloads and the drop down is reset to SAR and SAR currency is shown on the products.

This is my code in my-module/observer/changecurrency.php

if($country=='saudi'){
  $currency = 'SAR';
  $this->storeManager->getStore()->setCurrentCurrencyCode($currency);
}

Here I want to check whether the user selected the USD currency or not. If the user selects USD, I have to show products in USD currency, otherwise I have to show the products in SAR currency.

1
Can you give your full observer code here?Debajit Guha
You will need to show your code for us to find your issue, and also supply a list of which steps you have done in order to solve the issue. Please read stackoverflow.com/help/how-to-ask for help with improving you question, and thus improving the likelyhood of someone answering your question.Aron Cederholm
I didn't quite understand your use-case with AED. If the user doesn't select USD as currenct, then AED should be selected instead of SAR? That sounds a bit odd. Can you verify if that is what you meant?Aron Cederholm
its a mistake . If the user doesn't select USD as currenct, then Riyal should be shownAbilash Erikson

1 Answers

0
votes

You are passing an incorrect $currency value to $this->storeManager->getStore()->setCurrentCurrencyCode($currency)

You have to pass the correct currency code. For a list of accepted currency codes, please see which ones you have configured by calling and inspecting the results of:

$this->storeManager->getStore()->getAvailableCurrencyCodes()

Then you can pass the correct currency code to setCurrentCurrencyCode

if ('saudi' == $country){
    $currency = 'SAR';
    $this->storeManager->getStore()->setCurrentCurrencyCode($currency);
}