Getting all users with a Role in Liferay

Henrik Paul picture Henrik Paul · Jun 7, 2011 · Viewed 14.6k times · Source

I'm new to Liferay development in general, so feel free to point out if I'm going about stuff totally the wrong way.

I'm trying to get a DynamicQuery object of all users within a certain group (I'll use this object to further filter another query I'll do against the message board). The User interface seems to have a roleIds property that I might be able to use, since I already know the roleId I'm interested in. But I can't find the proper way to query if roleIds contains a certain value.

Any ideas on what I want to do?

PS: I would have the exact SQL query I could ask directly, but I'd rather use Liferay's own connection pool, without needing to do some weird ext project thingy.

Answer

AdrianRM picture AdrianRM · Jun 28, 2011

You don't need a DynamicQuery. These are the methods you are looking for in the classes that Dirk points out:

long[] UserServiceUtil.getRoleUserIds(long roleId)

or

long[] UserLocalServiceUtil.getRoleUserIds(long roleId)
List<User> UserLocalServiceUtil.getRoleUsers(long roleId)

Remember that the methods in the classes XXXLocalServiceUtil are not checking the permissions of the current user.

EDIT: If you are looking for all users with a given role within a given community:

long companyId= _X_; //Perhaps CompanyThreadLocal.getCompanyId() if you don't have it anywhere else?
Role role=RoleLocalServiceUtil.getRole(companyId, "Example Role");
Group group=GroupLocalServiceUtil.getGroup(companyId, "Example Community");
List<UserGroupRole> userGroupRoles = UserGroupRoleLocalServiceUtil.
                       getUserGroupRolesByGroupAndRole(groupId, role.getRoleId());
for(UserGroupRole userGroupRole:userGroupRoles){
    User oneUser=userGroupRole.getUser();
}