Custom Fields management with ExpandoBridge

Custom Fields management with ExpandoBridge

Sometimes you may need to work with custom fields from Java code (for example, to set so read custom field). ExpandoBridge should help you in this case. Each model with custom fields support has public ExpandoBridge getExpandoBridge(); method inherited from com.liferay.portal.kernel.model.ClassedModel.
With the ExpandoBridge you may:
  • create custom field: public void addAttribute(String name) throws PortalException;
  • set custom fields value: public void setAttribute(String name, Serializable value);
  • read custom field value: public Serializable getAttribute(String name);.
This utility class encapsulates custom fields management logic:


public class ExpandoHelper {

    private static final boolean SECURED = false;

    public static void setCustomField(ClassedModel model, String fieldName, int fieldType, Serializable fieldValue) {
        try {
            if (!model.getExpandoBridge().hasAttribute(fieldName)) {
                model.getExpandoBridge().addAttribute(fieldName, fieldType, SECURED);
            }
            model.getExpandoBridge().setAttribute(fieldName, fieldValue, SECURED);
        } catch (Exception e) {
            _log.error("Can not set custom field, cause: " + e.getMessage());
        }
    }

    public static Serializable getCustomFiled(ClassedModel model, String filedName, Serializable defaultValue) {
        try {
            return model.getExpandoBridge().getAttribute(filedName, SECURED);
        } catch (Exception e) {
            _log.warn("Can not get custom field, return default one: " + defaultValue);
            return defaultValue;
        }
    }

    public static String getCustomFiled(ClassedModel model, String filedName) {
        Serializable customFiled = getCustomFiled(model, filedName, null);
        return customFiled != null ? customFiled.toString() : null;
    }

    private static final Log _log = LogFactoryUtil.getLog(ExpandoHelper.class);

}


You can use it for example, to set user's custom field:

ExpandoHelper.setCustomField(user, "hobby", ExpandoColumnConstants.STRING, "Liferay");

or to read it:

String hobby = ExpandoHelper.getCustomFiled(user, "hobby");
Note: flag 'secured' is set to 'false' here to prevent security check for custom fields.

Comments

Post a Comment

Popular posts from this blog

Liferay Search Container Example

Liferay DXP - max upload file size

Liferay Keycloak integration