简体   繁体   English

Liferay 6.1-如何以编程方式向用户分配角色(在挂钩中)

[英]Liferay 6.1 - How to programatically assign a role to a user (in a hook)

I am using liferay 6.1.1 CE GA2 bundled with tomcat 7.0.27 and hsql. 我正在使用捆绑有tomcat 7.0.27和hsql的liferay 6.1.1 CE GA2。

I have created a hook on ExpandoValue where I want to assign a role to a user when I update his custom fields. 我在ExpandoValue上创建了一个钩子,当我更新用户的自定义字段时,我想在其中分配角色。 Here is what I have tried : 这是我尝试过的:

public class UserTagValueListener implements ModelListener<ExpandoValue>{
    @Override
    public void onAfterUpdate(ExpandoValue arg0) throws ModelListenerException {       
        long userId = arg0.getClassPK();
        long roleId = (long)1; //could be any role

        try {
            System.out.println("user roles : " + UserUtil.getRoles(userId));

            /* I tried these 4 lines with the same result */
            //UserLocalServiceUtil.addRoleUsers(roleId, new long[]{userId});
            //RoleLocalServiceUtil.addUserRoles(userId, new long[]{roleId});
            //UserUtil.addRole(userId, roleId);
            RoleUtil.addUser(roleId, userId);
        } catch (PortalException e) {
            e.printStackTrace();
        } catch (SystemException e) {
            e.printStackTrace();
        }
        System.out.println("user roles : " + UserUtil.getRoles(userId));
    }
}

When I check the roles before and after the line where I add a UserRole, it shows that the role has been added to my current user. 当我在添加UserRole的行之前和之后检查角色时,它表明该角色已添加到我的当前用户。 But once the execution is finished, the user does not have the role anymore. 但是一旦执行完成,用户将不再具有该角色。

What am I doing wrong? 我究竟做错了什么?

This worked for me. 这对我有用。 Type is the value which I am getting from the select box role in create account.jsp page 类型是我从create account.jsp页面中的选择框角色获取的值

 String[] usery = (String[])user.getExpandoBridge().getAttribute("Type"); 

 Role role = RoleLocalServiceUtil.getRole(company.getCompanyId(), usery[0]);

 UserLocalServiceUtil.addRoleUser(role.getRoleId(), user.getUserId());

 UserLocalServiceUtil.updateUser(user);

this worked for me: 这为我工作:

try {

    User newUser = .....
    long roleId = ....      

    Role role = RoleLocalServiceUtil.getRole(roleId);

    System.out.println("Found role : " + role.getRoleId());
    RoleUtil.addUser(role.getRoleId(), newUser.getUserId());
    UserLocalServiceUtil.updateUser(newUser);
    RoleLocalServiceUtil.updateRole(role);

} catch (Exception e) {
    e.printStackTrace();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM