0

I'm trying to set two buttons so depending of the language user can switch to the other.

In my default.php I have this, to change on click on the link AppController:

              <li class="nav-item">
                <?php 
                if (I18n::getLocale() !== 'en_US'){ ?>
                  <?= $this->Html->link('EN', ['action' => 'changeLang']); ?>
                  <?php
                }else{ ?>
                  <?= $this->Html->link('ES', ['action' => 'changeLang']); ?>
                <?php } ?>
              </li>       

My AppController

    public function changeLang():void
    {
        if (I18n::getLocale() !== 'en_US'){
            I18n::setLocale('en_US');
        }else{
            I18n::setLocale('es_ES');
        }
        $this->redirect($this->referer());

    }

My default.po (in locales/es/default.po)

#: ./src/Controller/AddressController.php:72
#: ./src/Controller/UserController.php:81
msgid "Usuario registrado."
msgstr "Registered user."

It goes in the correct lines but the code doesn't change. What I'm doing wrong?

I used var_char to see if it pass the ifs correctly and it does.

A also change the app.php in config to from

        'defaultLocale' => env('APP_DEFAULT_LOCALE', 'en_US'),

to

        'defaultLocale' => env('APP_DEFAULT_LOCALE', 'es_ES'),

and it also works.

If I use I18n::setLocale('es_ES'); on AppController inicialize it works, so why does it not work in my function?

Iria
  • 9
  • 4

1 Answers1

0

I18n::setLocale is a per-request setting. You're not doing anything in the code shown to save it to a session or cookie, so it will only ever be set to the default value when starting up, or to your specified value just before redirecting (which starts a new request, which resets to the default value).

Greg Schmidt
  • 5,010
  • 2
  • 14
  • 35
  • How can save it? I tried : Configure::write('idioma','es'); but when I call var_dump(Configure::read('idioma')); is NULL. I write it in the if before the link – Iria Jan 09 '23 at 15:34
  • Configure is also per request. Cookie or session as outlined above. – mark Jan 09 '23 at 15:57
  • I'm trying to add cookies but I don't know where to inicialize to be the default value. In appController I addedd: – Iria Jan 09 '23 at 16:31
  • *I'm trying to add cookies but I don't know where to inicialize to be the default value. In appController I addedd:$idioma=$this->request->getCookie($idiomacookie); and depending of the $idioma change setlocales. And in the method change the language using $idioma = $this->request->('idiomacookie',['value'=>'en_US']); – Iria Jan 09 '23 at 16:37