Thursday, 3 December 2015

How to read liferay portlepreferences and read particular key of the preferences

Many a times we like to read the preferences of the portlet which is not of the current portlet scope (Preferences of the other than the current portlet). Liferay provides API called "PortletPreferencesLocalServiceUtil" to get the portletpreferences object / value.

API has methods which returns the one of the two objects :

1) com.liferay.portal.model.PortletPreferences
   This will provide the model object of PortletPreferences. It will not support to directly fetch value of specified key. If we like to get handler to fetch directly value from the key then we need to convert the "com.liferay.portal.model.PortletPreferences" to "javax.portlet.PortletPreferences". Liferay provides the API for this conversion as well:

Here is the quick example:
   //Fetching the list of model object of PortletPreferences

   List<com.liferay.portal.model.PortletPreferences> portletPreferencesObj = PortletPreferencesLocalServiceUtil.getPortletPreferences(themeDisplay.getLayout().getPlid(), portletId);
  
   //Take out the xml / preferences of PortletPreferences Table


   String xmlValue = portletPreferencesObj.get(0).getPreferences();
  
   //Convert the xml into javax.portlet.PortletPreferences i.e. key value pair


   javax.portlet.PortletPreferences portletPreferencesObjWithKeyValue = com.liferay.portlet.PortletPreferencesFactoryUtil.fromDefaultXML(xmlValue);

  
   //Once we have converted portlet preference object we can fetch value of the specified key. "studentId" in our case
                           
   String studentId = portletPreferencesObjWithKeyValue.getValue("studentId",StringPool.BLANK);              


2) javax.portlet.PortletPreferences
    This allows to read the value of the specified key directly:
   
    Here is the quick example:   
    //Returns the "javax.portlet.PortletPreferences" Object

    javax.portlet.PortletPreferences portletPreferencesObj = PortletPreferencesLocalServiceUtil.getPreferences(themeDisplay.getCompanyId()
                            ,PortletKeys.PREFS_OWNER_ID_DEFAULT,PortletKeys.PREFS_OWNER_TYPE_LAYOUT,themeDisplay.getLayout().getPlid(),
                            portletId);
    //Once we have portlet preference object we can fetch value of the specified key. "studentId" in our case 

                          
    String studentId = portletPreferencesObj.getValue("studentId",StringPool.BLANK);   
           

Note: In above API "portletId" is the portletname along with the instance if it is instanceable portlet.                               

We are done!

Cheers!
Henal Saraiya