Search code examples
pluginsliferay-6portlet

Interacting with Liferay portlet configuration in the portlet class


In a Liferay 6.0 plugin MVC portlet, how do I access the portlet configuration from the portlet class?

Note that by "configuration" I mean values that are specific to an instance of the portlet and are not user-specific; if an administrator sets a portlet configuration value, it should take effect for all users.

e.g.:

public class MyPortlet extends MVCPortlet
{
  @Override
  public void doView(RenderRequest renderRequest, RenderResponse renderResponse)
    throws IOException, PortletException
  {
    // Fill in the blank; what goes here?
    String configValue = ?;

    renderRequest.setAttribute("some-key", configValue);        

    super.doView(renderRequest, renderResponse);
  }
}

Solution

  • You can leverage Liferay's PortletPreferences service to accomplish this:

    String portletInstanceId = (String) renderRequest.getAttribute(WebKeys.PORTLET_ID);
    
    PortletPreferences config = PortletPreferencesFactoryUtil.getPortletSetup(request, portletInstanceId);
    
    // To retrieve a value from configuration:
    String value = config.getValue("key", "default value");
    
    // To store a value:
    config.setValue("key", newValue);
    config.store();
    

    It's a little confusing because it's named PortletPreferences (implies user-specific preferences) instead of something like PortletConfiguration (implies admin-controlled global configuration)... so just think of it as preferences for the portlet instance that are not specific to any user.