Tuesday, April 7, 2015

[Liferay] Access Liferay Services in Theme or Web Content using Velocity

Sometime, we need to get some data in our web contents. Well, using velocity, we can get the data we want. Create a simple structure and a template. You can assign that structure to some web content later.

Make sure your template script is VM. The below lines of code are for reference, they should help you to get the actual requirement done.

To get namespace of the portlet,
#set ($namespace = $request.get('portlet-namespace'))

To get company id
#set($companyId = $getterUtil.getLong($request.get("theme-display").get("company-id")))

In the line above you also get themeDisplay which can get you many more things. We have $request object here.

To get user service we can use $serviceLocator.
#set($userLocalService = $serviceLocator.findService("com.liferay.portal.service.UserLocalService"))

If you're unable to get $serviceLocator check portal-ext.properties for the property below and set accordingly.

# Set a comma delimited list of variables the Velocity engine cannot
# have access to. This will affect Dynamic Data List templates, Journal
# templates, and Portlet Display templates.
#
velocity.engine.restricted.variables=serviceLocator

Get user from the service
#set($user = $userLocalService.getUserByScreenName($companyId, "kravigupta"))

Get phone service
#set($phoneLocalService = $serviceLocator.findService("com.liferay.portal.service.PhoneLocalService"))

Get all phone numbers of user
#set($userPhones = $phoneLocalService.getPhones($companyId, "com.liferay.portal.model.Contact", $user.getContact().getContactId()))

You can even use validator
#if($validator.isNull($user))
<div>The user is null.</div>
#end

Hope this helps.


No comments:

Post a Comment

Note: Only a member of this blog may post a comment.