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

Domestic-to-international connection at Orlando (MCO)

Find non-case sensitive string in a mixed list of elements?

0-rank tensor vs vector in 1D

Is it convenient to ask the journal's editor for two additional days to complete a review?

Prepend last line of stdin to entire stdin

Why the difference in type-inference over the as-pattern in two similar function definitions?

Recycling old answers

Yu-Gi-Oh cards in Python 3

Method for adding error messages to a dictionary given a key

Is there a difference between "Fahrstuhl" and "Aufzug"

Running a General Election and the European Elections together

How to check if all elements of 1 list are in the *same quantity* and in any order, in the list2?

WOW air has ceased operation, can I get my tickets refunded?

Calculator final project in Python

I believe this to be a fraud - hired, then asked to cash check and send cash as Bitcoin

Does increasing your ability score affect your main stat?

Does Germany produce more waste than the US?

Is wanting to ask what to write an indication that you need to change your story?

Necessary condition on homology group for a set to be contractible

Axiom Schema vs Axiom

Why don't programming languages automatically manage the synchronous/asynchronous problem?

Is a distribution that is normal, but highly skewed considered Gaussian?

How to avoid supervisors with prejudiced views?

Why isn't the Mueller report being released completely and unredacted?



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










0















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!










share|improve this question
















bumped to the homepage by Community 14 mins ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.



















    0















    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!










    share|improve this question
















    bumped to the homepage by Community 14 mins ago


    This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.

















      0












      0








      0


      1






      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!










      share|improve this question
















      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






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 1 '17 at 18:20







      hezided

















      asked Oct 31 '17 at 15:08









      hezidedhezided

      3019




      3019





      bumped to the homepage by Community 14 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 14 mins ago


      This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.






















          1 Answer
          1






          active

          oldest

          votes


















          0














          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 the frontend scope as it is only defined in etc/frontend/di.xml. The "magic" happens in the getTargetStore() 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 the getDefaultStoreById() calls with getTargetStore().


          • 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.


          • 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 an if 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.






          share|improve this answer

























            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
            );



            );













            draft saved

            draft discarded


















            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









            0














            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 the frontend scope as it is only defined in etc/frontend/di.xml. The "magic" happens in the getTargetStore() 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 the getDefaultStoreById() calls with getTargetStore().


            • 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.


            • 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 an if 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.






            share|improve this answer





























              0














              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 the frontend scope as it is only defined in etc/frontend/di.xml. The "magic" happens in the getTargetStore() 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 the getDefaultStoreById() calls with getTargetStore().


              • 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.


              • 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 an if 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.






              share|improve this answer



























                0












                0








                0







                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 the frontend scope as it is only defined in etc/frontend/di.xml. The "magic" happens in the getTargetStore() 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 the getDefaultStoreById() calls with getTargetStore().


                • 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.


                • 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 an if 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.






                share|improve this answer















                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 the frontend scope as it is only defined in etc/frontend/di.xml. The "magic" happens in the getTargetStore() 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 the getDefaultStoreById() calls with getTargetStore().


                • 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.


                • 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 an if 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.







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Oct 9 '18 at 0:57

























                answered Oct 9 '18 at 0:50









                LoganLogan

                22614




                22614



























                    draft saved

                    draft discarded
















































                    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.




                    draft saved


                    draft discarded














                    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





















































                    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







                    Popular posts from this blog

                    Nidaros erkebispedøme

                    Birsay

                    Was Woodrow Wilson really a Liberal?Was World War I a war of liberals against authoritarians?Founding Fathers...