Vinod
Vinod

Reputation: 2311

How can I assign a role to a user in Liferay

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();
            }
        }

Upvotes: 0

Views: 579

Answers (1)

Parkash Kumar
Parkash Kumar

Reputation: 4730

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

Upvotes: 2

Related Questions