I want to update the quote item price on switching the currency from the frontend.
Is there any event to track currency switch option and give me the previous currency and requested currency?
Magento Stack Exchange is a question and answer site for users of the Magento e-Commerce platform. It only takes a minute to sign up.
Sign up to join this communityI want to update the quote item price on switching the currency from the frontend.
Is there any event to track currency switch option and give me the previous currency and requested currency?
I would recommend to write a Plugin on the following Controller Action :
Magento\Directory\Controller\Currency\SwitchAction
For example:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Directory\Controller\Currency\Switch">
<plugin name="yournamespace_yourmodule_directory_currency_switch_plugin"
type="YourNamespace\YourModule\Plugin\Magento\Direcotry\Controller\Currency\SwitchAction"
sortOrder="10"
disabled="false"/>
</type>
</config>
And then you could use the following code:
<?php
namespace YourNamespace\YourModule\Plugin\Magento\Directory\Controller\Currency;
class SwitchAction
{
protected $storeManager;
public function __construct(
\Magento\Store\Model\StoreManagerInterface $storeManager
) {
$this->storeManager= $storeManager;
}
public function beforeExecute(
\Magento\Directory\Controller\Currency\SwitchAction $subject,
$result
) {
$currentCurrency = $this->storeManager->getStore()->getCurrentCurrencyCode();
$newCurrency = (string)$this->getRequest()->getParam('currency');
// your code here
}
}
[Magento Version 2.4.x]
app/code/VendorName/ModuleName/etc/frontend
di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Directory\Controller\Currency\SwitchAction">
<plugin name="custom_action_on_currency_switch"
type="VendorName\ModuleName\Plugin\Direcotry\Controller\Currency\SwitchAction"
sortOrder="10"/>
</type>
</config>
app/code/VendorName/ModuleName/Plugin/Direcotry/Controller/Currency
SwitchAction.php
<?php
namespace VendorName\ModuleName\Plugin\Direcotry\Controller\Currency;
use Magento\Directory\Controller\Currency\SwitchAction as SwitchActionParent;
class SwitchAction
{
/**
* Currency switcher before plugin
*
* @param SwitchActionParent $subject
*
* @return void
*/
public function beforeExecute(SwitchActionParent $subject)
{
$newCurrency = (string) $subject->getRequest()->getParam('currency');
echo "New Currency ".$newCurrency;
// Add your code here.
}
}