wintercms / wn-translate-plugin

Translate plugin for Winter CMS
MIT License
13 stars 18 forks source link

How to set language from frontend? #43

Closed gviabcua closed 2 years ago

gviabcua commented 2 years ago

How to set language from frontend? This don`t work

$translator = Translator::instance();
$translator->setLocale($locale, true);
mjauvin commented 2 years ago

Why not use the localeSwitcher component?

gviabcua commented 2 years ago

Why not use the localeSwitcher component?

No, I am using personal language for each user. And need to change language after user login.

mjauvin commented 2 years ago

Then you need to redirect to the right location

mjauvin commented 2 years ago

look at how the LocalePicker component does it. ref. https://github.com/wintercms/wn-translate-plugin/blob/main/components/LocalePicker.php#L75-L92

  public function onSwitchLocale()
  {
      if (!$locale = post('locale')) {
          return;
      }

      // Remember the current locale before switching to the requested one
      $this->oldLocale = $this->translator->getLocale();

      $this->translator->setLocale($locale);

      $pageUrl = $this->withPreservedQueryString($this->makeLocaleUrlFromPage($locale), $locale);
      if ($this->property('forceUrl')) {
          return Redirect::to($this->translator->getPathInLocale($pageUrl, $locale));
      }

      return Redirect::to($pageUrl);
  }
gviabcua commented 2 years ago

look at how the LocalePicker component does it. ref. https://github.com/wintercms/wn-translate-plugin/blob/main/components/LocalePicker.php#L75-L92

  public function onSwitchLocale()
  {
      if (!$locale = post('locale')) {
          return;
      }

      // Remember the current locale before switching to the requested one
      $this->oldLocale = $this->translator->getLocale();

      $this->translator->setLocale($locale);

      $pageUrl = $this->withPreservedQueryString($this->makeLocaleUrlFromPage($locale), $locale);
      if ($this->property('forceUrl')) {
          return Redirect::to($this->translator->getPathInLocale($pageUrl, $locale));
      }

      return Redirect::to($pageUrl);
  }

This work so good! Thanks