Friday, August 22, 2014

[Liferay] Get and Set portlet preferences in liferay | In Portlet Class and JSP

We often need to get and set preferences of a portlet. Here is few simple lines to do the job.

To get preferences of portlet, from the portlet class using actionRequest use

final PortletPreferences preferences = getPortletPreferences(actionRequest);

To get preferences of portlet, from the portlet class using renderRequest use

final PortletPreferences preferences = getPortletPreferences(renderRequest);

There are other methods as well. If we get get portletResource then to get preferences use the code below.

final String portletResource = ParamUtil.getString(portletRequest, "portletResource");

PortletPreferences preferences = null;
try {
preferences = PortletPreferencesFactoryUtil.getPortletSetup(portletRequest, portletResource);
} catch (final Exception e) {
LOG.error(e.getMessage(), e);
}

if (preferences == null) {
preferences = portletRequest.getPreferences();
}

In the JSP get the preferences using

PortletPreferences preferences = renderRequest.getPreferences();

To store preferences
preferences.setValue("key", value);
preferences.store();

Thats It! :)