How to update UserIndicator?

Hello!
I have an edit screen, where the currently logged-in user can change some of his data, e.g. forename, lastname, etc.
On onPostCommit() I try to update the UserIndicator in the mainscreen with:

public UserIndicator userIndicator;

public void onPostCommit(final DataContext.PostCommitEvent event) {

userIndicator.refreshUser();

Now I have this.userIndicator is Null. Yes, I can understand that, but what is the initialization here?
Thanks in advance,

ciao
HP

Hi,

UserIndicator is located in the MainScreen and can be accessed in it. So the task is to notify MainScreen that a user has changed. One of the options if to create ApplicationEvent that is fired from UserEdit and handled in the MainScreen, e.g.:

public class UserUpdatedEvent extends ApplicationEvent {

    public UserUpdatedEvent(String username) {
        super(username);
    }

    @Override
    public String getSource() {
        return (String) super.getSource();
    }
}
public class UserEdit extends StandardEditor<User> {

    ....

    @Subscribe(target = Target.DATA_CONTEXT)
    public void onPostCommit(DataContext.PostCommitEvent event) {
        ...

        getApplicationContext().getBean(UiEventPublisher.class)
                .publishEvent(new UserUpdatedEvent(getEditedEntity().getUsername()));
    }
}

Unfortunately, just call userIndicator.refreshUser() is not enough, because UserIndicator obtains user instance from currentUserSubstitution#getAuthenticatedUser which returns an old instance, thus you need to set userIndicatorFormatter:

public class MainScreen extends Screen implements Window.HasWorkArea {
    ...

    @Autowired
    private UserIndicator userIndicator;
    @Autowired
    private CurrentUserSubstitution currentUserSubstitution;
    @Autowired
    private DatabaseUserRepository databaseUserRepository;
    @Autowired
    private MetadataTools metadataTools;
    
    ...

    @Install(to = "userIndicator", subject = "formatter")
    private String userIndicatorFormatter(final UserDetails userDetails) {
        User user = databaseUserRepository.loadUserByUsername(userDetails.getUsername());
        return metadataTools.getInstanceName(user);
    }

    @EventListener
    public void onUserUpdated(UserUpdatedEvent event) {
        UserDetails authenticatedUser = currentUserSubstitution.getAuthenticatedUser();
        if (Objects.equals(authenticatedUser.getUsername(), event.getSource())) {
            userIndicator.refreshUser();
        }
    }
}

Demo project: UserIndicator-demo.zip (89.3 KB)

Gleb

2 Likes

Works instantly!
Thanks for the solution and thanks for all the extra time you spent on the explanation and providing demo project, too.
Br
HP