How can I assign a role to a user in Liferay

时光怂恿深爱的人放手 提交于 2019-12-25 12:27:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!