2

How to obtain Role of a logged in User in Liferay Themes? How to check if User belongs to a particular role?

Vikas V
  • 3,176
  • 2
  • 37
  • 60

2 Answers2

2

UserLocalService has hasRoleUser method which can be used to find out if User belongs to a particular role. Below code can be put in navigation.vm file under templates folder.

#set($UserLocalServiceUtil = $serviceLocator.findService("com.liferay.portal.service.UserLocalService"))
#if ($UserLocalServiceUtil.hasRoleUser(roleID, $user.getUserId())) // It takes roleID as input to check.
  //Proceed with whatever you want to 
#else
  //Proceed with something else

Note: Instead of com.liferay.portal.service.UserLocalService, if you use com.liferay.portal.service.UserLocalServiceUtil, as might be found in some resources like this then you will encounter below exception,

ERROR com.liferay.portal.kernel.bean.BeanLocatorException: org.springframework.beans.factory.NoSuchBeanDefinitionException: No
  bean named 'com.liferay.portal.service.UserLocalServiceUtil' is defined
  com.liferay.portal.kernel.bean.BeanLocatorException: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'com.liferay.portal.servi
ce.UserLocalServiceUtil' is defined

Another way is,

#set($role=$serviceLocator.findService("com.liferay.portal.service.RoleLocalService"))
$role.getUserRoles($user_id)
Vikas V
  • 3,176
  • 2
  • 37
  • 60
2

Just loop through the $user object defined in init.vm

#set ($user_roles = $user.getRoles())
#foreach($role in $user_roles)
   $role.name<br />
#end
experimenter
  • 768
  • 1
  • 9
  • 30