We can access Liferay Services in velocity templates. We have many liferay services which sometimes required to access in velocity files.We know that a theme contains many velocity template files.So it would be great to know how to access those services in these template files. This article explains how to access liferay services in our velocity templates with some easy examples.
What's Liferay Service?
Liferay follows service oriented architecture. A liferay service is simply method which can be invoked locally or externally. For example User Service which provides information about users of the portal, Organization Service which provides organization information of the portal and so on. We can have even our custom services also. So for simplicity accessing Liferay services means we are accessing liferay methods.
Example 1: Access Liferay User Service (UserLocalService)
#set($userLocalService = $serviceLocator.findService('com.liferay.portal.service.UserLocalService'))
Note 1: If you want to test the above code then copy the above line into your portal_normal.vm file of the current theme.
Note 2: You can call any method of UserLocalService by using the variable $userLocalService as written in the above code. For example $userLocalService.getUsersCount().
Note 3: Check Liferay source code for all the methods in UserLocalService
Example 2: Access Liferay Organization Service (OrganizationLocalService)
#set($organizationLocalService = $serviceLocator.findService('com.liferay.portal.service.OrganizationLocalService'))
<img class="alignleft size-full wp-image-506" src="https://proliferay.com/wp-content/uploads/2014/09/note.png" alt="Note" width="100" height="111" />
In this way we can access any liferay service.But what about custom services? I mean services under custom portlet. Will we be able to access custom services as explained in the above example? The answer is No. To access custom services we need to pass context path of the portlet in findService method.
Example 3: Access Custom Service (its part of custom portlet)
#set($bookService = $serviceLocator.findService("book-portlet", "com.proliferay.sbuilder.service.BookLocalService"))
Note 1 : book-portlet is the custom portlet.
Note 2: The service or portlet must be deployed before using it in the velocity templates.
Note 2: The context path of the portlet is the first parameter.
The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.