简体   繁体   中英

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.

I have created a hook on ExpandoValue where I want to assign a role to a user when I update his custom fields. 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. 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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