Change locale without login and reload page and messages

v2.3x

I use this:

VaadinSession.getCurrent().setLocale(locale);
UI.getCurrent().getPage().reload();

After the reload I can use .getLocale and and see that it works.
Get en, de, ru… depending on what is set in setLocale…

But how to reload the message texts…
When I change the locale on the login view, it works.
But not when I change it in a controller and then to the page reload…

KR
Roland

Hello Roland!

VaadinSession.getCurrent().setLocale(locale);
UI.getCurrent().getPage().reload();

This is the right way of changing locale, but the CurrentAuthentication still returns locale that was used in LoginView.
In general all XML loaders load messages with CurrentAuthentication#getLocale(), this is why nothing changes after page reloading. In this case, to change “login” locale you should reauthenticate user with new locale.

For instance:

@Autowired
private UserRepository userRepository;
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private CurrentAuthentication currentAuthentication;
@Autowired
private Notifications notifications;

@Subscribe(id = "changeLocaleBtn", subject = "clickListener")
public void onChangeLocaleBtnClick(final ClickEvent<JmixButton> event) {
    Authentication currAuth = currentAuthentication.getAuthentication();
    // If user has logged in through LoginView
    if (currAuth.getDetails() instanceof ClientDetails currDetails) {
        // Set new locale
        VaadinSession.getCurrent().setLocale(coreProperties.getAvailableLocales().g
        // Copy client details from current authentication and change locale
        ClientDetails newDetails = ClientDetails.builder().of(currDetails)
                .locale(VaadinSession.getCurrent().getLocale())
                .build();
        // Use system token since we cannot get raw user's password.
        // And set current authoritites
        SystemAuthenticationToken authentication = new SystemAuthenticationToken(
                currentAuthentication.getUser(),
                currentAuthentication.getUser().getAuthorities());
        authentication.setDetails(newDetails);
        
        Authentication newAuth;
        try {
            newAuth = authenticationManager.authenticate(authentication);
        } catch (AuthenticationException e) {
            notifications.create("Error on changing locale")
                    .withType(Notifications.Type.ERROR)
                    .show();
            return;
        }
        SecurityContextHelper.setAuthentication(newAuth);
        UI.getCurrent().getPage().reload();
    }
}
1 Like

late answer :slight_smile:

works fine, thx!