I had a case where I didn't want to use the enum's toString() method, rather I wanted to call a getLabel() method that does my GWT.create() call for i18n.
I didn't want to use toString() for the i18n as I want toString() to still work on the server side.
Here's the code to make to call a different method to get the text representation. It does the following:- Convert the value in the ComboBox with a property editor to call getLabel()
- Convert the values in the list with a ModelProcessor to call getLabel() and Template
The ComboBox that uses Condition enum (with a getLabel() method for i18n)
Code:
final SimpleComboBox<Condition> combo = new SimpleComboBox<Condition>();
combo.setFieldLabel("Condition");
combo.setName("condition");
combo.add(Arrays.asList(Condition.values()));
combo.setEditable(false);
combo.setAllowBlank(false);
combo.setTriggerAction(TriggerAction.ALL);
combo.setSimpleValue(Condition.NEW);
Code:
// Replace the text in the box with the enums label
ListModelPropertyEditor<SimpleComboValue<Condition>> propEditor =
new ListModelPropertyEditor<SimpleComboValue<Condition>>()
{
public String getStringValue(SimpleComboValue<Condition> value) {
return value.getValue().getLabel();
}
};
propEditor.setDisplayProperty("label");
combo.setPropertyEditor(propEditor);
// Replace the text in the list with the enums labels
combo.getView().setModelProcessor(new ModelProcessor<SimpleComboValue<Condition>>() {
public SimpleComboValue<Condition> prepareData(SimpleComboValue<Condition> model) {
model.set("label", model.getValue().getLabel());
return model;
}
});
// Use getLabel in list (by default SimpleComboBox displayProperty "value" is used - calls enum toString)
String html = "<tpl for=\".\"><div role=\"listitem\" class=\"" + combo.getListStyle() + "-item\">{" + "label" + "}</div></tpl>";
combo.setTemplate(html);
Verbose, but not too tricky. Hope this helps someone do the same.