Set store cookie not working in Magento 2 The Next CEO of Stack OverflowSet custom price of product when adding to cart code not workingMagento 2.1.6 Cannot save shipmentMagento 2 cookie is not set on homepageadmin grid not workingMagento 2: After custom cookie is created all pages default to home pageHow to solve Front controller reached 100 router match iterations in magento2Magento 2 Front controller reached 100 router match iterations issueMagento 2.3 Can't view module's front end page output?Deleted ShipperHQ module causing error in “All Customers” section of Magento 2“Area code is not set” in var/log
Why do remote US companies require working in the US?
Are police here, aren't itthey?
Can you be charged for obstruction for refusing to answer questions?
How to check if all elements of 1 list are in the *same quantity* and in any order, in the list2?
Writing differences on a blackboard
Rotate a column
Prepend last line of stdin to entire stdin
Why, when going from special to general relativity, do we just replace partial derivatives with covariant derivatives?
How I can get glyphs from a fraktur font and use them as identifiers?
Can I use the load factor to estimate the lift?
Won the lottery - how do I keep the money?
I believe this to be a fraud - hired, then asked to cash check and send cash as Bitcoin
Is the D&D universe the same as the Forgotten Realms universe?
Why isn't the Mueller report being released completely and unredacted?
Find non-case sensitive string in a mixed list of elements?
When you upcast Blindness/Deafness, do all targets suffer the same effect?
Is it my responsibility to learn a new technology in my own time my employer wants to implement?
Is wanting to ask what to write an indication that you need to change your story?
Running a General Election and the European Elections together
What did we know about the Kessel run before the prequels?
Why don't programming languages automatically manage the synchronous/asynchronous problem?
The past simple of "gaslight" – "gaslighted" or "gaslit"?
How many extra stops do monopods offer for tele photographs?
What is meant by "large scale tonal organization?"
Set store cookie not working in Magento 2
The Next CEO of Stack OverflowSet custom price of product when adding to cart code not workingMagento 2.1.6 Cannot save shipmentMagento 2 cookie is not set on homepageadmin grid not workingMagento 2: After custom cookie is created all pages default to home pageHow to solve Front controller reached 100 router match iterations in magento2Magento 2 Front controller reached 100 router match iterations issueMagento 2.3 Can't view module's front end page output?Deleted ShipperHQ module causing error in “All Customers” section of Magento 2“Area code is not set” in var/log
I'm trying to make my first Magento 2 module so I'm new to this...
Basically what I'm trying to achieve now is:
check if a store view was set in a cookie before
if yes: do nothing.
if not: set English store view.
this is my code:
<?php
namespace HeziDebbyGeoIpRedirectPlugin;
use HeziDebbyGeoIpRedirectModelGeoIpRequest;
use MagentoFrameworkAppFrontControllerInterface;
use MagentoFrameworkAppRequestInterface;
use MagentoStoreApiStoreCookieManagerInterface;
use MagentoStoreModelPluginStoreCookie;
use MagentoStoreModelStoreFactory;
class GeoIpRedirectPlugin
/**
* @var StoreFactory
*/
private $storeFactory;
/**
* @var StoreCookieManagerInterface
*/
private $storeCookieManager;
/**
* @var GeoIpRequest
*/
private $geoIpRequest;
/**
* @var StoreCookie
*/
private $storeCookie;
public function __construct(
StoreFactory $storeFactory,
StoreCookieManagerInterface $storeCookieManager,
GeoIpRequest $geoIpRequest
)
$this->storeFactory = $storeFactory;
$this->storeCookieManager = $storeCookieManager;
$this->geoIpRequest = $geoIpRequest;
public function beforeDispatch(
FrontControllerInterface $subject,
RequestInterface $request
)
if(!$this->storeCookieManager->getStoreCodeFromCookie())
$store = $this->storeFactory->create();
$store->load('EN','country_code');
$this->storeCookieManager->setStoreCookie($store);
return null;
There are 2 things which I do not understand:
1) I'm debugging with Xdebug and I have set a breakpoint on the condition line, the weird thing is that in one page load, the debugging stops on this breakpoint more then once, why is that happening?
**edit: it happens because of other non related requests to frontcontroller
2) The cookie is not being set after this line
$this->storeCookieManager->setStoreCookie($store);
And in the next time the debugger stops on the condition, the cookie is set to the default store view(it actually loads the default store view the therefore the cookie is 'default).
Thanks in advance!
magento2 php
bumped to the homepage by Community♦ 5 mins ago
This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.
add a comment |
I'm trying to make my first Magento 2 module so I'm new to this...
Basically what I'm trying to achieve now is:
check if a store view was set in a cookie before
if yes: do nothing.
if not: set English store view.
this is my code:
<?php
namespace HeziDebbyGeoIpRedirectPlugin;
use HeziDebbyGeoIpRedirectModelGeoIpRequest;
use MagentoFrameworkAppFrontControllerInterface;
use MagentoFrameworkAppRequestInterface;
use MagentoStoreApiStoreCookieManagerInterface;
use MagentoStoreModelPluginStoreCookie;
use MagentoStoreModelStoreFactory;
class GeoIpRedirectPlugin
/**
* @var StoreFactory
*/
private $storeFactory;
/**
* @var StoreCookieManagerInterface
*/
private $storeCookieManager;
/**
* @var GeoIpRequest
*/
private $geoIpRequest;
/**
* @var StoreCookie
*/
private $storeCookie;
public function __construct(
StoreFactory $storeFactory,
StoreCookieManagerInterface $storeCookieManager,
GeoIpRequest $geoIpRequest
)
$this->storeFactory = $storeFactory;
$this->storeCookieManager = $storeCookieManager;
$this->geoIpRequest = $geoIpRequest;
public function beforeDispatch(
FrontControllerInterface $subject,
RequestInterface $request
)
if(!$this->storeCookieManager->getStoreCodeFromCookie())
$store = $this->storeFactory->create();
$store->load('EN','country_code');
$this->storeCookieManager->setStoreCookie($store);
return null;
There are 2 things which I do not understand:
1) I'm debugging with Xdebug and I have set a breakpoint on the condition line, the weird thing is that in one page load, the debugging stops on this breakpoint more then once, why is that happening?
**edit: it happens because of other non related requests to frontcontroller
2) The cookie is not being set after this line
$this->storeCookieManager->setStoreCookie($store);
And in the next time the debugger stops on the condition, the cookie is set to the default store view(it actually loads the default store view the therefore the cookie is 'default).
Thanks in advance!
magento2 php
bumped to the homepage by Community♦ 5 mins ago
This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.
add a comment |
I'm trying to make my first Magento 2 module so I'm new to this...
Basically what I'm trying to achieve now is:
check if a store view was set in a cookie before
if yes: do nothing.
if not: set English store view.
this is my code:
<?php
namespace HeziDebbyGeoIpRedirectPlugin;
use HeziDebbyGeoIpRedirectModelGeoIpRequest;
use MagentoFrameworkAppFrontControllerInterface;
use MagentoFrameworkAppRequestInterface;
use MagentoStoreApiStoreCookieManagerInterface;
use MagentoStoreModelPluginStoreCookie;
use MagentoStoreModelStoreFactory;
class GeoIpRedirectPlugin
/**
* @var StoreFactory
*/
private $storeFactory;
/**
* @var StoreCookieManagerInterface
*/
private $storeCookieManager;
/**
* @var GeoIpRequest
*/
private $geoIpRequest;
/**
* @var StoreCookie
*/
private $storeCookie;
public function __construct(
StoreFactory $storeFactory,
StoreCookieManagerInterface $storeCookieManager,
GeoIpRequest $geoIpRequest
)
$this->storeFactory = $storeFactory;
$this->storeCookieManager = $storeCookieManager;
$this->geoIpRequest = $geoIpRequest;
public function beforeDispatch(
FrontControllerInterface $subject,
RequestInterface $request
)
if(!$this->storeCookieManager->getStoreCodeFromCookie())
$store = $this->storeFactory->create();
$store->load('EN','country_code');
$this->storeCookieManager->setStoreCookie($store);
return null;
There are 2 things which I do not understand:
1) I'm debugging with Xdebug and I have set a breakpoint on the condition line, the weird thing is that in one page load, the debugging stops on this breakpoint more then once, why is that happening?
**edit: it happens because of other non related requests to frontcontroller
2) The cookie is not being set after this line
$this->storeCookieManager->setStoreCookie($store);
And in the next time the debugger stops on the condition, the cookie is set to the default store view(it actually loads the default store view the therefore the cookie is 'default).
Thanks in advance!
magento2 php
I'm trying to make my first Magento 2 module so I'm new to this...
Basically what I'm trying to achieve now is:
check if a store view was set in a cookie before
if yes: do nothing.
if not: set English store view.
this is my code:
<?php
namespace HeziDebbyGeoIpRedirectPlugin;
use HeziDebbyGeoIpRedirectModelGeoIpRequest;
use MagentoFrameworkAppFrontControllerInterface;
use MagentoFrameworkAppRequestInterface;
use MagentoStoreApiStoreCookieManagerInterface;
use MagentoStoreModelPluginStoreCookie;
use MagentoStoreModelStoreFactory;
class GeoIpRedirectPlugin
/**
* @var StoreFactory
*/
private $storeFactory;
/**
* @var StoreCookieManagerInterface
*/
private $storeCookieManager;
/**
* @var GeoIpRequest
*/
private $geoIpRequest;
/**
* @var StoreCookie
*/
private $storeCookie;
public function __construct(
StoreFactory $storeFactory,
StoreCookieManagerInterface $storeCookieManager,
GeoIpRequest $geoIpRequest
)
$this->storeFactory = $storeFactory;
$this->storeCookieManager = $storeCookieManager;
$this->geoIpRequest = $geoIpRequest;
public function beforeDispatch(
FrontControllerInterface $subject,
RequestInterface $request
)
if(!$this->storeCookieManager->getStoreCodeFromCookie())
$store = $this->storeFactory->create();
$store->load('EN','country_code');
$this->storeCookieManager->setStoreCookie($store);
return null;
There are 2 things which I do not understand:
1) I'm debugging with Xdebug and I have set a breakpoint on the condition line, the weird thing is that in one page load, the debugging stops on this breakpoint more then once, why is that happening?
**edit: it happens because of other non related requests to frontcontroller
2) The cookie is not being set after this line
$this->storeCookieManager->setStoreCookie($store);
And in the next time the debugger stops on the condition, the cookie is set to the default store view(it actually loads the default store view the therefore the cookie is 'default).
Thanks in advance!
magento2 php
magento2 php
edited Nov 1 '17 at 18:20
hezided
asked Oct 31 '17 at 15:08
hezidedhezided
3019
3019
bumped to the homepage by Community♦ 5 mins ago
This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.
bumped to the homepage by Community♦ 5 mins ago
This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
I recently struggled with this same dilemma - I went through 3 iterations of different approaches and finally found one that seems to be working:
- Create an interceptor (plugin) on the
MagentoStoreModelStoreResolver::getCurrentStoreId()
method - Utilize the
MagentoStoreModelStoreSwitcher
to switch to the desired store
Module Files
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="MagentoStoreModelStoreResolver">
<plugin name="my_custom_store_resolver_current_store_id" type="VendorModulePluginModelStoreResolverPlugin"/>
</type>
</config>
etc/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="VendorModulePluginModelStoreResolverPlugin">
<arguments>
<argument name="cache" xsi:type="object">MagentoFrameworkAppCacheTypeConfig</argument>
<argument name="runMode" xsi:type="init_parameter">MagentoStoreModelStoreManager::PARAM_RUN_TYPE</argument>
<argument name="scopeCode" xsi:type="init_parameter">MagentoStoreModelStoreManager::PARAM_RUN_CODE</argument>
</arguments>
</type>
</config>
Plugin/Model/StoreResolverPlugin
(the magic)
<?php
namespace VendorModulePluginModel;
/**
* Dependencies
*/
use MagentoFrameworkSerializeSerializerInterface;
use MagentoStoreModelStoreSwitcher;
/**
* Store Resolver Plugin
*/
class StoreResolverPlugin extends MagentoStoreModelStoreResolver
/**
* @var MagentoFrameworkSerializeSerializerInterface
*/
private $serializer;
/**
* @var MagentoStoreApiDataStoreInterface
*/
protected $_targetStore;
/**
* @var MagentoStoreModelStoreSwitcher
*/
protected $_storeSwitcher;
/**
* Get Target store
*
* @return MagentoStoreApiDataStoreInterface
*/
protected function getTargetStore()
if (!$this->_targetStore)
list($stores, $defaultStoreId) = $this->getStoresData();
$default = $this->getDefaultStoreById($defaultStoreId);
try
$this->_targetStore = $this->getRequestedStoreByCode('english');
catch (MagentoFrameworkExceptionNoSuchEntityException $e)
$this->_targetStore = $default;
// Switch stores
$this->getStoreSwitcher()->switch($default, $this->_targetStore, $this->_targetStore->getUrl());
return $this->_targetStore;
/**
* @inheritdoc
*/
public function aroundGetCurrentStoreId(MagentoStoreApiStoreResolverInterface $resolver, callable $proceed)
list($stores, $defaultStoreId) = $this->getStoresData();
$storeCode = $this->request->getParam(self::PARAM_NAME, $this->storeCookieManager->getStoreCodeFromCookie());
if (is_array($storeCode))
if (!isset($storeCode['_data']['code']))
throw new InvalidArgumentException(__('Invalid store parameter.'));
$storeCode = $storeCode['_data']['code'];
if ($storeCode)
try
$store = $this->getRequestedStoreByCode($storeCode);
catch (MagentoFrameworkExceptionNoSuchEntityException $e)
$store = $this->getTargetStore();
if (!in_array($store->getId(), $stores))
$store = $this->getTargetStore();
else
$store = $this->getTargetStore();
return $store->getId();
/**
* Get serializer
*
* @return MagentoFrameworkSerializeSerializerInterface
* @deprecated 100.2.0
*/
private function getSerializer()
if ($this->serializer === null)
$this->serializer = MagentoFrameworkAppObjectManager::getInstance()
->get(SerializerInterface::class);
return $this->serializer;
/**
* Get store switcher
*
* @return MagentoStoreModelStoreSwitcher
*/
private function getStoreSwitcher()
if ($this->_storeSwitcher === null)
$this->_storeSwitcher = MagentoFrameworkAppObjectManager::getInstance()
->get(StoreSwitcher::class);
return $this->_storeSwitcher;
Notes
- The plugin is completely overriding the
getCurrentStoreId()
method. This is only executed on thefrontend
scope as it is only defined inetc/frontend/di.xml
. The "magic" happens in thegetTargetStore()
method. You can load stores via the store repository as I did here, or you can choose to load them another way if you want to include more dependencies.- The main difference with the overridden
getCurrentStoreId()
method is the replacement of thegetDefaultStoreById()
calls withgetTargetStore()
.
- The main difference with the overridden
- It seems that the only reason this works is because the store switch is only executed once:
- The first time the script is run,
$this->_targetStore
is not yet defined and the switch is executed.
- The first time the script is run,
- If you would like to redirect your users to another store URL, I believe the place to do that would be right after the
$this->getStoreSwitcher()->switch()
call. - My implementation encloses the contents of
aroundGetCurrentStoreId()
in anif
statement that check if my module is enabled. If not, I call$proceed()
.
I would definitely love to hear whether or not this works for your case and if you have any other thoughts or ideas to consider.
add a comment |
Your Answer
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "479"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f199475%2fset-store-cookie-not-working-in-magento-2%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
I recently struggled with this same dilemma - I went through 3 iterations of different approaches and finally found one that seems to be working:
- Create an interceptor (plugin) on the
MagentoStoreModelStoreResolver::getCurrentStoreId()
method - Utilize the
MagentoStoreModelStoreSwitcher
to switch to the desired store
Module Files
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="MagentoStoreModelStoreResolver">
<plugin name="my_custom_store_resolver_current_store_id" type="VendorModulePluginModelStoreResolverPlugin"/>
</type>
</config>
etc/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="VendorModulePluginModelStoreResolverPlugin">
<arguments>
<argument name="cache" xsi:type="object">MagentoFrameworkAppCacheTypeConfig</argument>
<argument name="runMode" xsi:type="init_parameter">MagentoStoreModelStoreManager::PARAM_RUN_TYPE</argument>
<argument name="scopeCode" xsi:type="init_parameter">MagentoStoreModelStoreManager::PARAM_RUN_CODE</argument>
</arguments>
</type>
</config>
Plugin/Model/StoreResolverPlugin
(the magic)
<?php
namespace VendorModulePluginModel;
/**
* Dependencies
*/
use MagentoFrameworkSerializeSerializerInterface;
use MagentoStoreModelStoreSwitcher;
/**
* Store Resolver Plugin
*/
class StoreResolverPlugin extends MagentoStoreModelStoreResolver
/**
* @var MagentoFrameworkSerializeSerializerInterface
*/
private $serializer;
/**
* @var MagentoStoreApiDataStoreInterface
*/
protected $_targetStore;
/**
* @var MagentoStoreModelStoreSwitcher
*/
protected $_storeSwitcher;
/**
* Get Target store
*
* @return MagentoStoreApiDataStoreInterface
*/
protected function getTargetStore()
if (!$this->_targetStore)
list($stores, $defaultStoreId) = $this->getStoresData();
$default = $this->getDefaultStoreById($defaultStoreId);
try
$this->_targetStore = $this->getRequestedStoreByCode('english');
catch (MagentoFrameworkExceptionNoSuchEntityException $e)
$this->_targetStore = $default;
// Switch stores
$this->getStoreSwitcher()->switch($default, $this->_targetStore, $this->_targetStore->getUrl());
return $this->_targetStore;
/**
* @inheritdoc
*/
public function aroundGetCurrentStoreId(MagentoStoreApiStoreResolverInterface $resolver, callable $proceed)
list($stores, $defaultStoreId) = $this->getStoresData();
$storeCode = $this->request->getParam(self::PARAM_NAME, $this->storeCookieManager->getStoreCodeFromCookie());
if (is_array($storeCode))
if (!isset($storeCode['_data']['code']))
throw new InvalidArgumentException(__('Invalid store parameter.'));
$storeCode = $storeCode['_data']['code'];
if ($storeCode)
try
$store = $this->getRequestedStoreByCode($storeCode);
catch (MagentoFrameworkExceptionNoSuchEntityException $e)
$store = $this->getTargetStore();
if (!in_array($store->getId(), $stores))
$store = $this->getTargetStore();
else
$store = $this->getTargetStore();
return $store->getId();
/**
* Get serializer
*
* @return MagentoFrameworkSerializeSerializerInterface
* @deprecated 100.2.0
*/
private function getSerializer()
if ($this->serializer === null)
$this->serializer = MagentoFrameworkAppObjectManager::getInstance()
->get(SerializerInterface::class);
return $this->serializer;
/**
* Get store switcher
*
* @return MagentoStoreModelStoreSwitcher
*/
private function getStoreSwitcher()
if ($this->_storeSwitcher === null)
$this->_storeSwitcher = MagentoFrameworkAppObjectManager::getInstance()
->get(StoreSwitcher::class);
return $this->_storeSwitcher;
Notes
- The plugin is completely overriding the
getCurrentStoreId()
method. This is only executed on thefrontend
scope as it is only defined inetc/frontend/di.xml
. The "magic" happens in thegetTargetStore()
method. You can load stores via the store repository as I did here, or you can choose to load them another way if you want to include more dependencies.- The main difference with the overridden
getCurrentStoreId()
method is the replacement of thegetDefaultStoreById()
calls withgetTargetStore()
.
- The main difference with the overridden
- It seems that the only reason this works is because the store switch is only executed once:
- The first time the script is run,
$this->_targetStore
is not yet defined and the switch is executed.
- The first time the script is run,
- If you would like to redirect your users to another store URL, I believe the place to do that would be right after the
$this->getStoreSwitcher()->switch()
call. - My implementation encloses the contents of
aroundGetCurrentStoreId()
in anif
statement that check if my module is enabled. If not, I call$proceed()
.
I would definitely love to hear whether or not this works for your case and if you have any other thoughts or ideas to consider.
add a comment |
I recently struggled with this same dilemma - I went through 3 iterations of different approaches and finally found one that seems to be working:
- Create an interceptor (plugin) on the
MagentoStoreModelStoreResolver::getCurrentStoreId()
method - Utilize the
MagentoStoreModelStoreSwitcher
to switch to the desired store
Module Files
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="MagentoStoreModelStoreResolver">
<plugin name="my_custom_store_resolver_current_store_id" type="VendorModulePluginModelStoreResolverPlugin"/>
</type>
</config>
etc/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="VendorModulePluginModelStoreResolverPlugin">
<arguments>
<argument name="cache" xsi:type="object">MagentoFrameworkAppCacheTypeConfig</argument>
<argument name="runMode" xsi:type="init_parameter">MagentoStoreModelStoreManager::PARAM_RUN_TYPE</argument>
<argument name="scopeCode" xsi:type="init_parameter">MagentoStoreModelStoreManager::PARAM_RUN_CODE</argument>
</arguments>
</type>
</config>
Plugin/Model/StoreResolverPlugin
(the magic)
<?php
namespace VendorModulePluginModel;
/**
* Dependencies
*/
use MagentoFrameworkSerializeSerializerInterface;
use MagentoStoreModelStoreSwitcher;
/**
* Store Resolver Plugin
*/
class StoreResolverPlugin extends MagentoStoreModelStoreResolver
/**
* @var MagentoFrameworkSerializeSerializerInterface
*/
private $serializer;
/**
* @var MagentoStoreApiDataStoreInterface
*/
protected $_targetStore;
/**
* @var MagentoStoreModelStoreSwitcher
*/
protected $_storeSwitcher;
/**
* Get Target store
*
* @return MagentoStoreApiDataStoreInterface
*/
protected function getTargetStore()
if (!$this->_targetStore)
list($stores, $defaultStoreId) = $this->getStoresData();
$default = $this->getDefaultStoreById($defaultStoreId);
try
$this->_targetStore = $this->getRequestedStoreByCode('english');
catch (MagentoFrameworkExceptionNoSuchEntityException $e)
$this->_targetStore = $default;
// Switch stores
$this->getStoreSwitcher()->switch($default, $this->_targetStore, $this->_targetStore->getUrl());
return $this->_targetStore;
/**
* @inheritdoc
*/
public function aroundGetCurrentStoreId(MagentoStoreApiStoreResolverInterface $resolver, callable $proceed)
list($stores, $defaultStoreId) = $this->getStoresData();
$storeCode = $this->request->getParam(self::PARAM_NAME, $this->storeCookieManager->getStoreCodeFromCookie());
if (is_array($storeCode))
if (!isset($storeCode['_data']['code']))
throw new InvalidArgumentException(__('Invalid store parameter.'));
$storeCode = $storeCode['_data']['code'];
if ($storeCode)
try
$store = $this->getRequestedStoreByCode($storeCode);
catch (MagentoFrameworkExceptionNoSuchEntityException $e)
$store = $this->getTargetStore();
if (!in_array($store->getId(), $stores))
$store = $this->getTargetStore();
else
$store = $this->getTargetStore();
return $store->getId();
/**
* Get serializer
*
* @return MagentoFrameworkSerializeSerializerInterface
* @deprecated 100.2.0
*/
private function getSerializer()
if ($this->serializer === null)
$this->serializer = MagentoFrameworkAppObjectManager::getInstance()
->get(SerializerInterface::class);
return $this->serializer;
/**
* Get store switcher
*
* @return MagentoStoreModelStoreSwitcher
*/
private function getStoreSwitcher()
if ($this->_storeSwitcher === null)
$this->_storeSwitcher = MagentoFrameworkAppObjectManager::getInstance()
->get(StoreSwitcher::class);
return $this->_storeSwitcher;
Notes
- The plugin is completely overriding the
getCurrentStoreId()
method. This is only executed on thefrontend
scope as it is only defined inetc/frontend/di.xml
. The "magic" happens in thegetTargetStore()
method. You can load stores via the store repository as I did here, or you can choose to load them another way if you want to include more dependencies.- The main difference with the overridden
getCurrentStoreId()
method is the replacement of thegetDefaultStoreById()
calls withgetTargetStore()
.
- The main difference with the overridden
- It seems that the only reason this works is because the store switch is only executed once:
- The first time the script is run,
$this->_targetStore
is not yet defined and the switch is executed.
- The first time the script is run,
- If you would like to redirect your users to another store URL, I believe the place to do that would be right after the
$this->getStoreSwitcher()->switch()
call. - My implementation encloses the contents of
aroundGetCurrentStoreId()
in anif
statement that check if my module is enabled. If not, I call$proceed()
.
I would definitely love to hear whether or not this works for your case and if you have any other thoughts or ideas to consider.
add a comment |
I recently struggled with this same dilemma - I went through 3 iterations of different approaches and finally found one that seems to be working:
- Create an interceptor (plugin) on the
MagentoStoreModelStoreResolver::getCurrentStoreId()
method - Utilize the
MagentoStoreModelStoreSwitcher
to switch to the desired store
Module Files
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="MagentoStoreModelStoreResolver">
<plugin name="my_custom_store_resolver_current_store_id" type="VendorModulePluginModelStoreResolverPlugin"/>
</type>
</config>
etc/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="VendorModulePluginModelStoreResolverPlugin">
<arguments>
<argument name="cache" xsi:type="object">MagentoFrameworkAppCacheTypeConfig</argument>
<argument name="runMode" xsi:type="init_parameter">MagentoStoreModelStoreManager::PARAM_RUN_TYPE</argument>
<argument name="scopeCode" xsi:type="init_parameter">MagentoStoreModelStoreManager::PARAM_RUN_CODE</argument>
</arguments>
</type>
</config>
Plugin/Model/StoreResolverPlugin
(the magic)
<?php
namespace VendorModulePluginModel;
/**
* Dependencies
*/
use MagentoFrameworkSerializeSerializerInterface;
use MagentoStoreModelStoreSwitcher;
/**
* Store Resolver Plugin
*/
class StoreResolverPlugin extends MagentoStoreModelStoreResolver
/**
* @var MagentoFrameworkSerializeSerializerInterface
*/
private $serializer;
/**
* @var MagentoStoreApiDataStoreInterface
*/
protected $_targetStore;
/**
* @var MagentoStoreModelStoreSwitcher
*/
protected $_storeSwitcher;
/**
* Get Target store
*
* @return MagentoStoreApiDataStoreInterface
*/
protected function getTargetStore()
if (!$this->_targetStore)
list($stores, $defaultStoreId) = $this->getStoresData();
$default = $this->getDefaultStoreById($defaultStoreId);
try
$this->_targetStore = $this->getRequestedStoreByCode('english');
catch (MagentoFrameworkExceptionNoSuchEntityException $e)
$this->_targetStore = $default;
// Switch stores
$this->getStoreSwitcher()->switch($default, $this->_targetStore, $this->_targetStore->getUrl());
return $this->_targetStore;
/**
* @inheritdoc
*/
public function aroundGetCurrentStoreId(MagentoStoreApiStoreResolverInterface $resolver, callable $proceed)
list($stores, $defaultStoreId) = $this->getStoresData();
$storeCode = $this->request->getParam(self::PARAM_NAME, $this->storeCookieManager->getStoreCodeFromCookie());
if (is_array($storeCode))
if (!isset($storeCode['_data']['code']))
throw new InvalidArgumentException(__('Invalid store parameter.'));
$storeCode = $storeCode['_data']['code'];
if ($storeCode)
try
$store = $this->getRequestedStoreByCode($storeCode);
catch (MagentoFrameworkExceptionNoSuchEntityException $e)
$store = $this->getTargetStore();
if (!in_array($store->getId(), $stores))
$store = $this->getTargetStore();
else
$store = $this->getTargetStore();
return $store->getId();
/**
* Get serializer
*
* @return MagentoFrameworkSerializeSerializerInterface
* @deprecated 100.2.0
*/
private function getSerializer()
if ($this->serializer === null)
$this->serializer = MagentoFrameworkAppObjectManager::getInstance()
->get(SerializerInterface::class);
return $this->serializer;
/**
* Get store switcher
*
* @return MagentoStoreModelStoreSwitcher
*/
private function getStoreSwitcher()
if ($this->_storeSwitcher === null)
$this->_storeSwitcher = MagentoFrameworkAppObjectManager::getInstance()
->get(StoreSwitcher::class);
return $this->_storeSwitcher;
Notes
- The plugin is completely overriding the
getCurrentStoreId()
method. This is only executed on thefrontend
scope as it is only defined inetc/frontend/di.xml
. The "magic" happens in thegetTargetStore()
method. You can load stores via the store repository as I did here, or you can choose to load them another way if you want to include more dependencies.- The main difference with the overridden
getCurrentStoreId()
method is the replacement of thegetDefaultStoreById()
calls withgetTargetStore()
.
- The main difference with the overridden
- It seems that the only reason this works is because the store switch is only executed once:
- The first time the script is run,
$this->_targetStore
is not yet defined and the switch is executed.
- The first time the script is run,
- If you would like to redirect your users to another store URL, I believe the place to do that would be right after the
$this->getStoreSwitcher()->switch()
call. - My implementation encloses the contents of
aroundGetCurrentStoreId()
in anif
statement that check if my module is enabled. If not, I call$proceed()
.
I would definitely love to hear whether or not this works for your case and if you have any other thoughts or ideas to consider.
I recently struggled with this same dilemma - I went through 3 iterations of different approaches and finally found one that seems to be working:
- Create an interceptor (plugin) on the
MagentoStoreModelStoreResolver::getCurrentStoreId()
method - Utilize the
MagentoStoreModelStoreSwitcher
to switch to the desired store
Module Files
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="MagentoStoreModelStoreResolver">
<plugin name="my_custom_store_resolver_current_store_id" type="VendorModulePluginModelStoreResolverPlugin"/>
</type>
</config>
etc/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="VendorModulePluginModelStoreResolverPlugin">
<arguments>
<argument name="cache" xsi:type="object">MagentoFrameworkAppCacheTypeConfig</argument>
<argument name="runMode" xsi:type="init_parameter">MagentoStoreModelStoreManager::PARAM_RUN_TYPE</argument>
<argument name="scopeCode" xsi:type="init_parameter">MagentoStoreModelStoreManager::PARAM_RUN_CODE</argument>
</arguments>
</type>
</config>
Plugin/Model/StoreResolverPlugin
(the magic)
<?php
namespace VendorModulePluginModel;
/**
* Dependencies
*/
use MagentoFrameworkSerializeSerializerInterface;
use MagentoStoreModelStoreSwitcher;
/**
* Store Resolver Plugin
*/
class StoreResolverPlugin extends MagentoStoreModelStoreResolver
/**
* @var MagentoFrameworkSerializeSerializerInterface
*/
private $serializer;
/**
* @var MagentoStoreApiDataStoreInterface
*/
protected $_targetStore;
/**
* @var MagentoStoreModelStoreSwitcher
*/
protected $_storeSwitcher;
/**
* Get Target store
*
* @return MagentoStoreApiDataStoreInterface
*/
protected function getTargetStore()
if (!$this->_targetStore)
list($stores, $defaultStoreId) = $this->getStoresData();
$default = $this->getDefaultStoreById($defaultStoreId);
try
$this->_targetStore = $this->getRequestedStoreByCode('english');
catch (MagentoFrameworkExceptionNoSuchEntityException $e)
$this->_targetStore = $default;
// Switch stores
$this->getStoreSwitcher()->switch($default, $this->_targetStore, $this->_targetStore->getUrl());
return $this->_targetStore;
/**
* @inheritdoc
*/
public function aroundGetCurrentStoreId(MagentoStoreApiStoreResolverInterface $resolver, callable $proceed)
list($stores, $defaultStoreId) = $this->getStoresData();
$storeCode = $this->request->getParam(self::PARAM_NAME, $this->storeCookieManager->getStoreCodeFromCookie());
if (is_array($storeCode))
if (!isset($storeCode['_data']['code']))
throw new InvalidArgumentException(__('Invalid store parameter.'));
$storeCode = $storeCode['_data']['code'];
if ($storeCode)
try
$store = $this->getRequestedStoreByCode($storeCode);
catch (MagentoFrameworkExceptionNoSuchEntityException $e)
$store = $this->getTargetStore();
if (!in_array($store->getId(), $stores))
$store = $this->getTargetStore();
else
$store = $this->getTargetStore();
return $store->getId();
/**
* Get serializer
*
* @return MagentoFrameworkSerializeSerializerInterface
* @deprecated 100.2.0
*/
private function getSerializer()
if ($this->serializer === null)
$this->serializer = MagentoFrameworkAppObjectManager::getInstance()
->get(SerializerInterface::class);
return $this->serializer;
/**
* Get store switcher
*
* @return MagentoStoreModelStoreSwitcher
*/
private function getStoreSwitcher()
if ($this->_storeSwitcher === null)
$this->_storeSwitcher = MagentoFrameworkAppObjectManager::getInstance()
->get(StoreSwitcher::class);
return $this->_storeSwitcher;
Notes
- The plugin is completely overriding the
getCurrentStoreId()
method. This is only executed on thefrontend
scope as it is only defined inetc/frontend/di.xml
. The "magic" happens in thegetTargetStore()
method. You can load stores via the store repository as I did here, or you can choose to load them another way if you want to include more dependencies.- The main difference with the overridden
getCurrentStoreId()
method is the replacement of thegetDefaultStoreById()
calls withgetTargetStore()
.
- The main difference with the overridden
- It seems that the only reason this works is because the store switch is only executed once:
- The first time the script is run,
$this->_targetStore
is not yet defined and the switch is executed.
- The first time the script is run,
- If you would like to redirect your users to another store URL, I believe the place to do that would be right after the
$this->getStoreSwitcher()->switch()
call. - My implementation encloses the contents of
aroundGetCurrentStoreId()
in anif
statement that check if my module is enabled. If not, I call$proceed()
.
I would definitely love to hear whether or not this works for your case and if you have any other thoughts or ideas to consider.
edited Oct 9 '18 at 0:57
answered Oct 9 '18 at 0:50
LoganLogan
22614
22614
add a comment |
add a comment |
Thanks for contributing an answer to Magento Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f199475%2fset-store-cookie-not-working-in-magento-2%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown