How to assign a role to a user in Liferay

Is there any API method for finding roleId using role name? I get the excel form role name, I need to check if the role name exists or not.

If the role exists

How can I assign this role to a user?

If the role does not exist,

How can I create a role first and then assign this role to the 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(); } } 
0
source share
1 answer

The following code might be useful in your 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); 
+2
source

Source: https://habr.com/ru/post/1238859/


All Articles