Reputation: 1
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?
Upvotes: 0
Views: 5133
Reputation: 94
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);
Upvotes: 1
Reputation: 3133
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();
}
Upvotes: 0