Friday, November 19, 2010

Spring Property Editor for an Enumeration with Localized Names

Problem statement:
  • You use a property editor when you bind a nested Enumeration field of a form backing object.
  • You have localized names for the values.
When you write your PropertyEditor you should remember that the getAsText() method needs to take care of the translation:

@Override
public String getAsText() {

if(getValue() == null) {
return null;
}

SurveyStatus status = (SurveyStatus)getValue();
return status.getTranslatedName();
}

while the setAsText() method does not:

@Override
public void setAsText(String surveyStatusStr) {

if (logger.isDebugEnabled()) {
logger.debug("Read string [" + surveyStatusStr + "] for the survey status field");
}

SurveyStatus status = null;

if (surveyStatusStr.compareTo(SurveyStatus.ACTIVE.toString()) == 0) {
status = SurveyStatus.ACTIVE;
}
else if (surveyStatusStr.compareTo(SurveyStatus.INACTIVE.toString()) == 0) {
status = SurveyStatus.INACTIVE;
}

setValue(status);
}

This is because Spring implicitly uses the enumeration name for the value of your tag, not the translated name.
E.g. If you have a select tag, this is what Spring does for you:

<option value="ACTIVE" ... >

It makes sense, of course...

No comments: