Setting Custom User Model Attributes in Liferay

Oftentimes you will need to extend Liferay’s built-in User model by adding custom attributes, such as a list of preferred settings. Fortunately, Liferay provides developers with an ExpandoBridge implementation to do so.

Thus, in order to add custom attributes simply use the Custom Fields option via the Control Panel (or programmatically). Search for the User model and add your custom field(s). In order to programmatically access these properties you now have two options. First, you may iterate over all custom fields set, or access custom fields through their key.

Access List of Custom Attributes

The following code snippet shows how to access the list of custom attributes set:

Map<String, Serializable> customAttributes = userLiferay
  .getExpandoBridge().getAttributes();
Iterator<String> it = customAttributes.keySet().iterator();

while (it.hasNext()) {
  String attribute = it.next();
  Serializable attributeValue = customAttributes.get(attribute);
  System.out.println("user custom attribute " + attribute + "="
    + attributeValue);
}

NOTE:
When getting NULL instead of your desired value when using getAttribute be sure to check for corrects permissions.

Access Specific Custom Attribute

The other option is to access specific custom fields by using its key through ExpandoValueLocalServiceUtil, as shown below:

String userBookmarksString = (String) ExpandoValueLocalServiceUtil
  .getData(Long.parseLong(PropsUtil.get("default-companyId")),
    userExpBridge.getClassName(), "CUSTOM_FIELDS",
    "yourCustomField", userExpBridge.getClassPK());

Updating Custom Attributes

Finally, in case you need to update a custom field use the following code:

ExpandoValue expVal = ExpandoValueLocalServiceUtil
  .getValue(Long.parseLong(PropsUtil.get("default-companyId")),
    userExpBridge.getClassName(), "CUSTOM_FIELDS",
    "yourCustomField", userExpBridge.getClassPK());
expVal.setData("newValue");
ExpandoValueLocalServiceUtil.updateExpandoValue(expVal);

That’s it!

You may also like...

1 Response

  1. Leandro says:

    Man, you save my day! Thank you very much!

Leave a Reply

Your email address will not be published. Required fields are marked *