问题
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();
}
}
回答1:
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);
来源:https://stackoverflow.com/questions/32557938/how-can-i-assign-a-role-to-a-user-in-liferay