简体   繁体   中英

Cakephp 4 can't change locales

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM