How to get the translation of an enumeration field?

105 Views Asked by At

In an entity, I have an enumeration field which is translated in english and french.

In the same entity, I have a computed field that I am using as a toString, so I would like to build the computed field with the enumeration value translated in english or french, depending on the user's locale.

My question : in the getter of my computed field written in the extension of the entity, how could I get the user's locale and translate the enumeration value ?

1

There are 1 best solutions below

0
On BEST ANSWER

You have to make your extension aware of its execution context. There are several interfaces that you can implement in your extensions so that they get injected with elements of their running context.

  1. org.jspresso.framework.model.component.IComponentFactoryAware to receive an ICompoentFactory instance
  2. org.jspresso.framework.security.ISubjectAware to receive the instance of the logged-in Subject
  3. org.jspresso.framework.application.backend.session.IApplicationSessionAware to receive the current instance of IApplicationSession
  4. org.jspresso.framework.model.entity.IEntityLifecycleHandlerAware to receive an instance of IEntityLifecycleHandler

In order to fulfill your use-case, the 4th interface must be implemented. Your extension will be injected with an instance of IEntityLifecycleHandler through the following method :

void setEntityLifecycleHandler(IEntityLifecycleHandler);

Just store this instance in your extension implementation as an instance parameter and use it afterwards in your code by safely casting it as a org.jspresso.framework.application.IController.

For instance :

public String getI18nLabel() {
  String translationKey = "ENUM_NAME." + getComponent().getEnumValue();
  IController controller = (IController) lifecycleHandler;
  return controller.getTranslation(translationKey, controller.getLocale());
}

Just remember that the pattern for the I18N resource bundle key of enumerations is ${ENUM_NAME}.${ENUM_VALUE} which is computed as the translationKey local variable in the code above.