Many to many association blacklist

Hi there!

I have two Entities: A User and a Role. They are in a many to many relation.

I want to open the User Edit Screen to add a Role to that User. If I add a Role to the User the Roles which are already associated to the User shouldn’t appear in the list of the Loopup Screen. How do I do that?

This is what I tried, but it does not work:

UserEdit.java:

public void onRoleAdd(Component source) {
    Map<String, Object> blacklist = CollectionUtils.createMap("blacklist", new HashSet<>());
    if (getItem() != null && getItem().getCurrentRoles() != null) {
        blacklist = CollectionUtils.createMap("blacklist", getItem().getCurrentRoles());
    }

    openLookup("profilegen$Role.browse", item -> add(item),
        WindowManager.OpenType.DIALOG,
        blacklist);
}

private void add(Collection item) {
    Role role = (Role) item.iterator().next();
    Set<Role> roles = getItem().getCurrentRoles();
    roles.add(role);
    getItem().setCurrentRole(roles);
    //TODO: roles are not added!
}

EDIT:
The RoleBrowse ScreenControler looks like this:

public class RoleBrowse extends QuickSearchLookup{

    @Inject
    private CollectionDatasource<Role, UUID> rolesDs;

    private Set<Role> blacklist;

    @Override
    public void init(Map<String, Object> params){
        getDialogOptions().setHeight(800.0f);
        blacklist = (Set<Role>) params.get("blacklist");
        updateBlacklist();
        setSearchChangeListener(x -> {
            updateBlacklist();
            return null;
        });
    }

    private void updateBlacklist() {
        if (blacklist != null) {
            blacklist.forEach(role -> rolesDs.excludeItem(role));
        }
    }
}

Clarification:
Excluding the Items in the RoleBrowse screen works well! My problem is that the Role is not added to the user, when I save the user. The Role appears in the UserEdit Screen. But When I hit save and reopen the User, the Role is gone.

Role successfully excluded:
RoleSuccesfullyExcluded

New Role added:
NewRoleAdded

after saving the user and reopening it the role is gone:
RoleGone

Hi,

How do you handle the blacklist parameter in the roles lookup screen? It should work similar to ProductBrowse screen mentioned in the Passing Parameters to a Screen recipe.

Thanks for your reply. I edited the question.

I see your problem now. Instead of adding the role to the collection attribute directly, add it to the datasource that holds the collection. Then the datasource will save it on the screen commit.

1 Like

Ah, thank you very much. So I edited the function:

private void add(Collection item) {
        Role role = (Role) item.iterator().next();
        userRolesDs.addItem(role);
}

and it worked. :slight_smile:

We are working on simplifying the API and making it straightforward, so in version 7.0 your initial code adding an item right to the collection will work.