How can I assign a role to a user in Liferay
Asked Answered
D

1

0

Is there any API method to find the roleId using role name? I am getting the role name(s) form an excel sheet, I need to check, whether the role name exists or not.

If role exist

how can I assign that role to user?

If role doesn't exist,

how can I create the role first and then assign that role to user?

My code,

if(role != null && !role.isEmpty()){
            Role currentRole=RoleLocalServiceUtil.getRole(companyId,role.trim());

            if(currentRole != null)
            {
                roleId = currentRole.getRoleId();
            }
            else{
                Role newRole = RoleServiceUtil.addRole(role.trim(), null, null, 0);
                roleId = newRole.getRoleId();
            }
        }
Duckpin answered 14/9, 2015 at 5:39 Comment(6)
#32473193Tambac
Do you want to create and assign general / site role(s)?Tambac
General Roles. I have updated my question, Which is not working Please let me know what is the issue.Duckpin
And how are you getting that role object?Tambac
That role is a string object, where I am getting the role name from excel sheetDuckpin
Didn't my answer meet your requirement?Tambac
T
2

The following code might be helpful in you case:

String roleName = "role name";

// Get role by name
Role role = RoleLocalServiceUtil.getRole(companyId, roleName);

// If role doesn't exist, create new using roleName
if(role == null){
    role = RoleServiceUtil.addRole(roleName, null, null, 0);
}

// Get user by userId and add role to it
User user = UserLocalServiceUtil.getUserById(userId);
UserLocalServiceUtil.addRoleUser(role.getRoleId(), user.getUserId());
UserLocalServiceUtil.updateUser(user);
Tambac answered 14/9, 2015 at 7:9 Comment(1)
If you want to add group roles, you can refer #29645990Tambac

© 2022 - 2024 — McMap. All rights reserved.