Вопрос

I am trying to set base currency pro-grammatically with below code.

class Currency extends \Magento\Framework\App\Action\Action
{
  protected $_storeManager;
   public function __construct(
     \Magento\Backend\Block\Template\Context $context, 
     \Magento\Store\Model\StoreManagerInterface $storeManager,
     array $data = []
      ) {     
      $this->_storeManager = $storeManager;
      parent::__construct($context, $data);
   }
   public function execute() {  
    $currencyCode = 'USD';
    $this->_storeManager->getStore()->setCurrentCurrencyCode($currencyCode);

  }
}

The above code is not setting the base currency, can anyone tell me where i am wrong? Thanks in Advance!!.

Update

I followed Rohan answer, then getting below error.

enter image description here

Here product prices in basket showing with changed currency, but order summary still showing with the old currency.

Это было полезно?

Решение

For base currency change, I would like to recommend you to change from admin configuration.

Store -> Configuration -> General -> Currency Setup -> Currency Options -> Base Currency

For programmatically, You need to inject this below code in your construct :

/**
 * @var \Magento\Framework\View\Result\PageFactory
 */
protected $_configInterface;

public function __construct(
    ....
    \Magento\Framework\App\Config\ConfigResource\ConfigInterface $configInterface
    ....
) {
    ....
    $this->_configInterface = $configInterface;
    ....
}

Then, you need to use this below line in your function :

$currency_code = "USD";
$this->_configInterface->saveConfig('currency/options/base', $currency_code, $store = \Magento\Framework\App\Config\ScopeConfigInterface::SCOPE_TYPE_DEFAULT, $scopeId = 0);

Hope, It will useful for you.

Другие советы

Try this

   $this->_storeManager->getStore()->setBaseCurrentCurrencyCode($currencyCode);

OR

   $this->_storeManager->getStore()->setBaseCode($currencyCode);
Лицензировано под: CC-BY-SA с атрибуция
Не связан с magento.stackexchange
scroll top